Подтвердить что ты не робот

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>

С#:

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" и хочу, чтобы это отразилось на ярлыках пользовательского интерфейса. Я установил Content как привязку, но что-то не так. Что я здесь делаю неправильно?

4b9b3361

Ответ 1

Вы можете создать свойство зависимости MyFoo и установить DataContext в свой экземпляр Window1:

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

Подробнее см. статью.

Создание MyFoo свойство зависимостей не является обязательным. он может работать только с свойством, если вы установите значение свойства перед назначением DataContext. (Но никогда с полем.) Однако, если вы хотите, чтобы метки отображали изменяющиеся значения W1 и W2 (или вы не знаете/не заботитесь, установлены ли значения до или после назначения DataContect), вам нужно Foo быть либо DependencyObject, либо реализовать интерфейс INotifyPropertyChanged.

Ответ 2

Или дайте вашему окну имя: например 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>