c# - 绑定(bind)数据模板控件属性

标签 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>

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

public string Service
{ get; set; }

我该怎么办?

最佳答案

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

在这种情况下,我将 UserControl 命名为“UI”(Name="UI"),因此您可以使用 ElementName 进行绑定(bind)>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));
        }
    }
}

结果:

enter image description here

关于c# - 绑定(bind)数据模板控件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14390743/

相关文章:

c# - 如何设置两个单元格之间的空间

c# - 挂接到 WPF 窗口中的 Windows 消息循环会在内部添加白色边框

c# - TreeViewItem 中的背景不是全宽

c# - 在 WPF 中显示来 self 的网络摄像头的视频流?

WPF:将命令添加到通过绑定(bind)菜单项自动生成

c# - 如何更新 mongodb 文档以向数组添加新项目?

c# - 使用通用类定义导入数据文件

.net - 文本框的值消失 - 将 View 模型绑定(bind)到选项卡(内容控件)

c# - 从 PrincipalContext 中查找域组件

c# - 如何在网格单击时显示子窗口(使用 mvvm 方法)