【问题标题】:Binding DataTemplate Control Property绑定 DataTemplate 控件属性
【发布时间】:2013-01-01 16:19:57
【问题描述】:

我有一个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>

我想将TextBlock 控件的Text 属性绑定到我的UserControl 类的属性,例如:

public string Service
{ get; set; }

我该怎么办?

【问题讨论】:

  • 您是否正确设置了 DataContext,因为这对我来说看起来不错。
  • @sa_ddam213 如何正确设置 DataContext?

标签: c# wpf binding datatemplate


【解决方案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 字符串更改时更新 UI

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));
        }
    }
}

结果:

【讨论】:

    猜你喜欢
    • 2012-09-06
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 2013-03-23
    • 2012-04-11
    • 1970-01-01
    相关资源
    最近更新 更多