Связывание свойства элемента управления DataTemplate

У меня есть UserControl вроде следующего:

<UserControl>
    <Expander> 
        <Expander.HeaderTemplate>
            <DataTemplate>
                <Grid HorizontalAlignment="{Binding Path=HorizontalAlignment, RelativeSource={RelativeSource AncestorType={x:Type ContentPresenter}}, Mode=OneWayToSource}">
                    <TextBlock Text="{Binding Path=Service, Mode=TwoWay}"/>
                </Grid>
            </DataTemplate>
        </Expander.HeaderTemplate>            
    </Expander>
</UserControl>

Я хочу привязать свойство Text элемента управления TextBlock к свойству моего класса UserControl, например:

public string Service
{ get; set; }

Как я могу сделать?


person Nick    schedule 18.01.2013    source источник
comment
Правильно ли вы установили свой DataContext, потому что это выглядит хорошо для меня.   -  person sa_ddam213    schedule 18.01.2013
comment
@sa_ddam213 Как правильно установить DataContext?   -  person Nick    schedule 18.01.2013


Ответы (1)


Попробуйте установить DataContext на UserControl, чтобы вы могли получить доступ к свойствам

В этой ситуации я назвал UserControl "UI" (Name="UI"), чтобы вы могли выполнить привязку, используя ElementName Text="{Binding ElementName=UI, Path=Service}"

Пример:

<UserControl x:Class="WpfApplication8.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Name="UI">
    <Expander>
        <Expander.HeaderTemplate>
            <DataTemplate>
                <Grid HorizontalAlignment="{Binding Path=HorizontalAlignment, RelativeSource={RelativeSource AncestorType={x:Type ContentPresenter}}, Mode=OneWayToSource}">
                    <TextBlock Text="{Binding ElementName=UI, Path=Service}" />
                </Grid>
            </DataTemplate>
        </Expander.HeaderTemplate>
    </Expander>
</UserControl>

Код:

Я реализовал INotifyPropertyChanged, это позволит обновлять пользовательский интерфейс при изменении строки Service

public partial class UserControl1 : UserControl, INotifyPropertyChanged
{
    public UserControl1()
    {
        InitializeComponent();
        Service = "Test";
    }

    private string _service;
    public string Service
    {
        get { return _service; }
        set { _service = value; NotifyPropertyChanged("Service"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

Результат:

введите здесь описание изображения

person sa_ddam213    schedule 18.01.2013