【发布时间】:2019-10-16 17:13:56
【问题描述】:
所以我可能不太了解绑定,我想出了这个测试项目,我可以在其中以简单的方式展示我的问题。我需要在哪里更改项目以使绑定更新视图?
这是我的项目,如果你想下载它: https://1drv.ms/u/s!AqdZJMIRBGu7z1V8K1jXN9BQWFQ-?e=oxdlhL
这里有一些代码:
TestClass.cs:
public class TestClass
{
public string Text { get; set; } = "Default";
}
TestClassView.xaml:
<UserControl x:Class="Test.TestClassView" ...>
<Grid>
<TextBlock Text="{Binding TestClass.Text}" />
</Grid>
</UserControl>
TestClassView.xaml.cs:
public partial class TestClassView : UserControl
{
public TestClass TestClass
{
get { return (TestClass)GetValue(TestClassProperty); }
set { SetValue(TestClassProperty, value); }
}
public static readonly DependencyProperty TestClassProperty = DependencyProperty.Register("TestClass", typeof(TestClass), typeof(TestClassView), new PropertyMetadata(new TestClass() { Text = "Default"}));
public TestClassView()
{
InitializeComponent();
DataContext = this;
}
MainWindow.xaml:
<Window x:Class="Test.MainWindow" ...>
<Grid>
<WrapPanel Margin="10">
<Button Content="Test" Click="Button_Click" />
<local:TestClassView x:Name="TestClassView" TestClass="{Binding TestClass}" />
</WrapPanel>
</Grid>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private TestClass testClass = new TestClass() { Text = "DefaultProperty" };
public TestClass TestClass { get { return testClass; } set{ testClass = value; OnPropertyChanged(); } }
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
TestClass = new TestClass() { Text = "Test1" };
MessageBox.Show("Test 1 Done");
await Task.Delay(1000);
TestClassView.TestClass = new TestClass() { Text = "Test2" };
MessageBox.Show("Test 2 Done");
}
}
所以当我点击按钮时,首先我设置了 MainWindow 的 TestClass 实例,它绑定到 TestClassView 的 DependencyProperty 调用 TestClass。我也调用了 PropertyChanged,但 TestClassView 属性没有更新。
一秒钟后,在点击事件处理程序的第二部分,实际上设置了TestClassView TestClass 属性,并且视图将被更新。
那么如何修改代码,让绑定生效呢?
【问题讨论】:
标签: c# wpf data-binding