C# 如何使用模板选择器将数据绑定到用户控件
我正在WPF中使用数据网格的模板选择器 我有这个密码:C# 如何使用模板选择器将数据绑定到用户控件,c#,wpf,xaml,data-binding,C#,Wpf,Xaml,Data Binding,我正在WPF中使用数据网格的模板选择器 我有这个密码: <l:ProblemTemplateSelector x:Key="problemTemplateSelector"> <l:ProblemTemplateSelector.ArithmeticTemplate> <DataTemplate> <Grid Background="LightBlue">
<l:ProblemTemplateSelector x:Key="problemTemplateSelector">
<l:ProblemTemplateSelector.ArithmeticTemplate>
<DataTemplate>
<Grid Background="LightBlue">
<l:ArithmeticUserControl Problem="{Binding ElementName=this}" />
</Grid>
</DataTemplate>
</l:ProblemTemplateSelector.ArithmeticTemplate>
</l:ProblemTemplateSelector>
这是另一个从运动中衍生出来的类
public partial class ArithmeticUserControl : Exercise
{
public ArithmeticUserControl()
{
InitializeComponent();
}
public override Problem Problem
{
get
{
return base.Problem;
}
set
{
base.Problem = value;
Arithmetic p = (Arithmetic)value;
Number1 = p.Number1;
Number2 = p.Number2;
Operator = p.Operation;
}
}
}
您应该能够将绑定声明为
“{binding}”
,并让它将问题
属性绑定到数据项
编辑:查看示例后,您需要更改处理问题的方式。WPF绑定系统不使用CLR属性,因此CLR属性的存在只是为了方便用户代码。因此,当通过绑定设置值时,属性中的代码永远不会执行
相反,您需要通过覆盖OnPropertyChanged
来处理属性值更改。例如,在继承的类中:
protected override OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
if(e.Property == ProblemProperty)
{
Arithmetic p = (Arithmetic)Problem;
Number1 = p.Number1;
Number2 = p.Number2;
Operator = p.Operation;
}
}
只需使用{Binding}
在控件中传递数据项。
如果这没有帮助,请在控件中添加一个TextBlock,并查看通过直接绑定绑定的内容:
<Grid Background="LightBlue">
<l:ArithmeticUserControl Problem="{Binding ElementName=this}" />
<TextBlock Text="{Binding}" Background="Green" ></TextBlock>
</Grid>
因此,在绿色背景上,您应该看到ListBoxItem中出现了什么Try out=“{Binding TemplatedParent}”,我说的“All the element”是一个模板化的元素,对吗?是的,但它不起作用,您能详细说明一下“All the element”是什么意思吗,绑定到ListBoxItem的控件本身或数据项?@Oscar:您如何确定它不工作?输出窗口中是否出现绑定错误?您是否正在监视已更改属性的,而它从未被调用以解决问题
?我只是在属性中放置断点。。那么,您认为我需要使用OnPropertyChanged吗?@oscar.imbres:绑定系统不使用包装器,您需要在register
方法中注册属性更改的回调(使用元数据重载,并在元数据中指定回调)如果你想监视这些更改,会是怎样的过载?@oscar:你要么重写OnPropertyChanged
,要么在依赖项属性本身附加一个处理程序(前者是更简单、更直接的选项,IMO)来检测更改。您的C#属性仅为方便而存在,绑定系统不使用它,这就是为什么只在其中使用GetValue
和SetValue
很重要的原因。它表示类型名称。我不明白为什么没有分配问题属性。您认为我需要对元数据做一些处理吗?
<Grid Background="LightBlue">
<l:ArithmeticUserControl Problem="{Binding ElementName=this}" />
<TextBlock Text="{Binding}" Background="Green" ></TextBlock>
</Grid>