繁体   English   中英

WPF:将Label绑定到类属性

[英]WPF: Binding a Label to a class property

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

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上的标签中反映出来。 我已将内容设置为绑定但有些事情是不对的。 我在这做错了什么?

您可以将MyFoo作为依赖项属性并将DataContext设置为Window1实例:

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...>

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

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

或者给你的Window命名:像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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM