WPF 绑定更改绑定源
本文关键字:绑定 WPF | 更新日期: 2023-09-27 17:56:07
我有以下类作为主窗口:
public partial class Window1 : Window
{
public Network network { get; set; }
public DataSet data_set { get; set; }
public Training training { get; set; }
public string CurrentFile { get; set; }
public MGTester tester;
public MCTester testerSSE;
public ChartWindow ErrorWindow;
public ChartWindow TimesWindow;
public Window1()
{
network = new Network();
data_set = new DataSet();
training = new Training();
tester = new MGTester();
testerSSE = new MCTester();
CurrentFile = "";
ErrorWindow = new ChartWindow();
TimesWindow = new ChartWindow();
InitializeComponent();
for (int i = 0; i < tester.GetDeviceCount(); ++i)
{
DeviceComboBox.Items.Add(tester.GetDeviceName(i));
}
}...
在我的 xaml 代码中,我有:
<ListView Grid.Row="0" x:Name="NetworkListview" ItemsSource="{Binding network.Layers}" IsSynchronizedWithCurrentItem="True">
<ListView.View>
<GridView>
<GridViewColumn Width="100" Header="layer name" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Width="60" Header="neurons" CellTemplate="{StaticResource NeuronsTemplate}"/>
<GridViewColumn Width="110" Header="activation" CellTemplate="{StaticResource ActivationTemplate}"/>
</GridView>
</ListView.View>
</ListView>
无论如何,我绑定到窗口1的某个成员...它工作正常,但我想更改控件绑定到的成员 -我的意思是我想在 Window1 中做类似的事情
this.network = new Network();
当我执行此绑定时停止工作 - 如何轻松轻松地"刷新"绑定?
如果绑定源不是 UI 类,请使用通知属性而不是自动属性。
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
public class MyClass : INotifyPropertyChanged
{
private Network _network;
public Network Network
{
get
{
return _network;
}
set
{
if (value != _network)
{
_network = value;
NotifyPropertyChanged(value);
}
}
}
protected NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
如果源类是 UI 类,请将网络定义为依赖项属性:
http://msdn.microsoft.com/en-us/library/system.windows.dependencyproperty.aspx
示例引用自上面的链接:
公共类 MyStateControl : ButtonBase{ public MyStateControl() : base() { } 公共布尔状态 { 获取 { 返回 (布尔值)this.GetValue(StateProperty);} 设置 { 这个。SetValue(StateProperty, value);} } public static readonly DependencyProperty StateProperty = DependencyProperty.Register( "State", typeof(Boolean), typeof(MyStateControl), new PropertyMetadata(false));}
有一种方法可以刷新绑定,但大多数时候,有更好的方法:将属性转换为依赖项属性,或将数据放入实现 INotifyPropertyChanged
接口的另一个类中。