WPF:将Label绑定到类属性

Gar*_*eth 23 c# wpf

我试图将标签的内容绑定到类实例的字符串属性,但没有太大成功.

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>
Run Code Online (Sandbox Code Playgroud)

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

即,当我单击按钮时,我将MyFoo的属性设置为"Hello"和"Dave",并希望在UI上的标签中反映出来.我已将内容设置为绑定但有些事情是不对的.我在这做错了什么?

Vla*_*lad 20

您可以创建MyFoo一个依赖项属性并将其设置DataContext为您的Window1实例:

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅此文章.

建立MyFoo依赖属性不是强制性的.如果分配之前设置属性值,它可能只与属性一起使用DataContext.(但从不使用字段.)但是,如果您希望标签获取W1和的更改值W2(或者您不知道/关心在分配之前或之后是否设置了值DataContect),则需要Foo为a DependencyObject,或实现接口INotifyPropertyChanged.

  • @Vlad 使用 `DependencyProperty` 和实现 `INotifyPropertyChanged` 之间有什么区别,或者这应该是一个问题本身? (2认同)

Arc*_*rus 8

或者给你的窗口命名:喜欢NameOfWindow并使用ElementName绑定:

Content="{Binding ElementName=NameOfWindow, Path=MyFoo.W1}"
Run Code Online (Sandbox Code Playgroud)

完整示例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> 
Run Code Online (Sandbox Code Playgroud)