绑定DataTemplate控件属性

时间:2013-01-18 00:43:27

标签: c# wpf binding 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; }

我该怎么办?

1 个答案:

答案 0 :(得分:3)

尝试将DataContext设置为UserControl,以便您可以访问属性

在这种情况下,我将UserControl“用户界面”命名为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));
        }
    }
}

结果:

enter image description here