我正在尝试将标签的内容绑定到类实例的字符串属性而没有太大成功。
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上的标签中。我已将内容设置为绑定但有些事情是不对的。我在这做错了什么?
答案 0 :(得分:20)
您可以将MyFoo
作为依赖项属性,并将DataContext
设置为Window1
个实例:
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>
有关详细信息,请参阅此article。
使MyFoo
依赖属性不是强制性的。如果在分配DataContext
之前设置属性值,它可能仅适用于属性。 (但从不使用字段。)但是,如果您希望标签获取W1
和W2
的更改值(或者您不知道/关心是否在分配之前或之后设置了值DataContect
),您需要Foo
为DependencyObject
或实施界面INotifyPropertyChanged
。
答案 1 :(得分:7)
或者给你的窗口命名:如NameOfWindow
并使用ElementName绑定:
Content="{Binding ElementName=NameOfWindow, Path=MyFoo.W1}"
完整样本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" Name="NameOfWindow">
<Grid>
<Label Height="28" Margin="12,55,106,0" Name="label1" Background="Bisque" Content="{Binding ElementName=NameOfWindow, Path=MyFoo.W1}" VerticalAlignment="Top" />
<Label Height="28" Margin="12,12,106,0" Name="label2" Background="Bisque" Content="{Binding ElementName=NameOfWindow, Path=MyFoo.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>