WPF:将标签绑定到类属性 [英] WPF: Binding a Label to a class property
问题描述
我试图将标签的内容绑定到类实例的字符串属性,但没有取得多大成功.
I'm trying to get the content of a label to bind to the string property of a class instance without much success.
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 上的标签中.我已将内容设置为绑定,但有些不对劲.我在这里做错了什么?
i.e. when I click the button, I set the properties of MyFoo to "Hello" and "Dave", and want that reflected in the labels on the UI. I've set the Content as a binding but something isn't right. What am I doing wrong here?
推荐答案
您可以将 MyFoo
设为依赖属性,并将 DataContext
设置为您的 Window1
实例:
You may make your MyFoo
a dependency property and set the DataContext
to your Window1
instance:
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>
查看这篇文章更多详情.
使 MyFoo
成为依赖属性不是强制性的.如果您在分配 DataContext
之前设置属性值,它可能只适用于一个属性.(但永远不要使用字段.)但是,如果您希望标签获取 W1
和 W2
的变化值(或者您不知道/关心这些值在分配 DataContect
之前或之后设置),你需要 Foo
要么是一个 DependencyObject
,要么实现接口 INotifyPropertyChanged
.
Making MyFoo
a dependency property is not compulsory. it may work with just a property if you set the property value before assigning the DataContext
. (But never with a field.) However if you want the labels to pick up the changing values of W1
and W2
(or you don't know/care if the values are set before or after assigning the DataContect
), you need Foo
to be either a DependencyObject
, or implement interface INotifyPropertyChanged
.
这篇关于WPF:将标签绑定到类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!