c# – 绑定DataTemplate控件属性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 绑定DataTemplate控件属性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1966字,纯文字阅读大概需要3分钟。
内容图文
![c# – 绑定DataTemplate控件属性](/upload/InfoBanner/zyjiaocheng/785/8b8591b9a893480bb41eeb3afd254c0d.jpg)
我有一个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设置为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,这将允许在服务字符串更改时更新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));
}
}
}
结果:
内容总结
以上是互联网集市为您收集整理的c# – 绑定DataTemplate控件属性全部内容,希望文章能够帮你解决c# – 绑定DataTemplate控件属性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。