c# - WPF:将标签绑定(bind)到类属性

标签 c# wpf

我试图让标签的内容绑定(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 之前设置属性值,它可能只使用一个属性。 (但永远不要使用字段。)但是,如果您希望标签获取 W1W2 的变化值(或者您不知道/不关心这些值在分配 DataContect 之前或之后设置),您需要 FooDependencyObject,或实现接口(interface) INotifyPropertyChanged.

关于c# - WPF:将标签绑定(bind)到类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2317229/

相关文章:

c# - 使我的应用程序 'full screen' (WPF) 时 Windows 任务栏出现异常行为

c# - WPF 组合框绑定(bind) : can't change selection

c# - 更改悬停 CSS 上的滚动条颜色

c# - 无法连接到 SQL Server 2008 R2

wpf - 使用模板 T4 生成 .xaml 和 .xaml.cs

c# - 如何在 WPF 中将多个组合框与一个数据源一起使用?

WPF 数据网格 : Lazy Loading/Inifinite scroll

c# - 在 Xamarin 项目中使用 Entity.FrameworkCore.Sqlite 时找不到程序集 'System.Memory'

c# - 如何在像素着色器中实现 super 采样/抗锯齿?

c# - 从 USB 打印机获取信息