我尝试将标签的内容绑定到类实例的字符串属性,但并没有取得太大成功。
XAML:
XAML:
<Window x:Class="WPFBindingTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Label Height="28" Margin="12,55,106,0" Name="label1" Background="Bisque"
Content="{Binding Source=MyFoo, Path=W1}" VerticalAlignment="Top" />
<Label Height="28" Margin="12,12,106,0" Name="label2" Background="Bisque"
Content="{Binding Source=MyFoo, Path=W2}" VerticalAlignment="Top" />
<Button Height="23" HorizontalAlignment="Right" Margin="0,0,32,48"
Name="button1" VerticalAlignment="Bottom" Width="89"
Click="button1_Click">
Set Properties
</Button>
</Grid>
</Window>
C#:
namespace WPFBindingTest
{
public partial class Window1 : Window
{
public Foo MyFoo;
public Window1()
{
InitializeComponent();
MyFoo = new Foo();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
MyFoo.W1 = "Hello";
MyFoo.W2 = "Dave";
}
}
public class Foo
{
public string W1 { get; set; }
public string W2 { get; set; }
}
}
即当我点击按钮时,我设置MyFoo的属性为“Hello”和“Dave”,并希望在UI标签上反映出来。 我已经将Content设置为绑定,但是有些不对劲。 我在这里做错了什么?
DependencyProperty
和实现INotifyPropertyChanged
之间有什么区别?或者这应该是一个单独的问题? - ywmINotifyPropertyChanged
更轻量级,DependencyProperty
如果未使用则不占用内存,并且可以用于动画、样式、模板,可以被继承(从父容器到包含的元素)等等。例如,请参见此答案。 - Vlad