假设我有一个UserControl,其DataContext设置为它的VM
现在假设UserControl定义了一个依赖项属性,我想最初绑定到ViewModel上的属性...如果顶层元素是UserControl,我将如何在UserControl的XAML中引用此属性?
<UserControl x:Class="TestApp1.TestControl"
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"
xmlns:local="clr-namespace:TestApp1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" x:Name="test">
</UserControl>
依赖属性:
public static readonly DependencyProperty MyTestPropProperty= null;
public string MyTestProp
{
get { return (string)GetValue(MyTestPropProperty); }
set { SetValue(MyTestPropProperty, value); }
}
static TestControl()
{
MyTestPropProperty= DependencyProperty.Register(
"MyTestProp",
typeof(string),
typeof(TestControl),
new FrameworkPropertyMetadata());
}
在XAML上,我希望能够去MyTestProp = {Binding yadda yadda},但我无法从XAML中引用它
答案 0 :(得分:0)
只需在根节点中添加属性,如下所示:
<Usercontrol xmlns=blablabla
MyProperty="{Binding MyViewModelProperty}">
编辑:这不起作用,因为没有对新创建的属性的XAML引用。使用<Style TargetType="TestControl">
或从外部上下文(包含此usercontrol的那个)设置属性