[英]Binding to a custom XAML control property won't work
我正在尝试使用C#和XAML创建Windows 10 UWP应用程序。 在这一点上,我对项目模板中的数据绑定非常感兴趣。
所以基本上,我有一个ViewModel,它绑定到XAML控件。
我想将数据模型绑定到自定义控件的属性。 问题是有些事情行之有效,有些却行不通,我真的不明白为什么。
因此,此绑定有效:
<GridView ItemsSource="{Binding MediaElementId}" >
<GridView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
但是,当我将其他东西插入TextBlock时,它将无法工作。
例如,这些绑定将不起作用 :
<TextBlock Text="{Binding Path=.}"/>
<controls:CustomControl Test="{Binding Path=., UpdateSourceTrigger=PropertyChanged}" />
<controls:CustomControl Test="{Binding Path=., RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}"/>
<controls:CustomControl Test="{Binding}"/>
因此,我基本上找到了文档,即{Binding}与{Binding Path =。}等效,但是在此示例中,它似乎并非如此。
您可以在一个我发现问题的项目中自己尝试: https : //bitbucket.org/MrGreeny/pivottestapp/src/4edee74acfac6dbb4f9f042acaf389cc6fd90a31?at=master
编辑:该属性是一个非常简单的属性:
private string test;
public string Test
{
get { return null; }
set
{
Debug.WriteLine(value);
//What i think should be here is for example textblock.Text = value
}
}
因此,基本上我要做的就是使用DependencyProperty
而不是常规属性。 这是有效的解决方案:
首先是DataTemplate
内部的控件:
<GridView ItemsSource="{Binding MediaElementId}" >
<GridView.ItemTemplate>
<DataTemplate>
<local:CustomControl TextBlockContent="{Binding}" />
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
然后在自定义控件xaml.cs
文件中:
首先是包装程序公开DependencyProperty
:
public string TextBlockContentProperty
{
get { return (string)GetValue(TextBlockContentPropertyProperty); }
set { SetValue(TextBlockContentPropertyProperty, value); }
}
然后是DependencyProperty
本身。
public static readonly DependencyProperty TextBlockContentPropertyProperty =
DependencyProperty.Register(
"TextBlockContentProperty",
typeof(string),
typeof(CustomControl),
new PropertyMetadata(0, new PropertyChangedCallback(OnTextChanged)) );
请注意,最后一个参数包含与OnTextChanged
函数的连接,在这里我们可以访问对象实例。 以上所有都是static
,我们不能使用它们来更改对象的实例。
这是我实现实例特定逻辑的方式。 TextBlockContent
是常规属性,它公开TextBlock
的Text
属性,即自定义控件的内容。
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CustomControl cc = d as CustomControl;
string content = (string)e.NewValue;
cc.TextBlockContent = content;
}
感谢所有回答我最初问题的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.