簡體   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