我试图让标签的内容绑定(bind)到类实例的字符串属性,但没有成功。
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 的标签中反射(reflect)出来。我已将内容设置为绑定(bind),但有些地方不对。我在这里做错了什么?
最佳答案
您可以使您的 MyFoo
成为依赖属性,并将 DataContext
设置为您的 Window1
实例:
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>
查看此 article了解更多详情。
使 MyFoo
成为依赖属性不是强制性的。如果您在分配 DataContext
之前设置属性值,它可能只使用一个属性。 (但永远不要使用字段。)但是,如果您希望标签获取 W1
和 W2
的变化值(或者您不知道/不关心这些值在分配 DataContect
之前或之后设置),您需要 Foo
是 DependencyObject
,或实现接口(interface) INotifyPropertyChanged
.
关于c# - WPF:将标签绑定(bind)到类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2317229/