gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:11:58 25 4
gpt4 key购买 nike

我有一个如下所示的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com