我想绑定在代码隐藏中定义的属性,以及在具有数据类型的同一模板中的类中定义的另一个属性。 这是一个例子:
我的课程:
public class MyClass
{
public string name { get; set; }
public MyClass(string name)
{
this.name=name;
}
}
代码背后:
public string name2;
public MyView()
{
this.InitializeComponent();
name2 = "Tim";
}
<DataTemplate x:Key="MasterListViewItemTemplate" x:DataType="model:MyClass">
<StackPanel>
<TextBlock Text="{x:Bind name}"/>
<TextBlock Text="{x:Bind name2}"/>
</StackPanel>
</DataTemplate>
在这种情况下,显然第一个TextBlock没有问题。 我希望第二个TextBlock引用代码隐藏而不是MyClass。
我该怎么办?
答案 0 :(得分:0)
您应该将第二个TextBlock的datacontext设置为当前窗口。 我认为这可以通过使用像这样的绑定表达式来实现
<TextBlock DataContext="{Binding ElementName=MyView, Path=.}" Text="{x:Bind name2}" />
其中绑定表达式中的MyView是MyView窗口的x:Name属性。
EDIT(WPF):此绑定甚至可以用于ResourceDictionary条目
<TextBlock DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=.}" Text="{Binding name2}" />
重要的是,我看到你的例子,name2只是在窗口的构造函数中定义的。正确的做法应该是这样的。
public string name2 { get; set; }
public MyView()
{
this.InitializeComponent();
this.name2 = "Tim";
}
我希望这会有所帮助。
答案 1 :(得分:0)
尝试以下方法:
在CodeBehind的构造函数中:
public MyView()
{
this.InitializeComponent();
this.DataContext = this; //set the datacontext here
name2 = "Tim";
}
在您的XAML中:
<TextBlock Text="{Binding DataContext.name2, ElementName=MyView}"/>
答案 2 :(得分:0)
首先,绑定始终首先查看自身的DataContext,如果没有指定,则按所有者遍历树到所有者,直到分配了DataContext。然后它在那里寻找要绑定的属性。由于您在两个文本块中都放置了相同的属性名称,并且未指定任何其他绑定方式,因此它们都在同一个DataContext中查找该属性。换句话说,他们都在看你的MyClass对象。
要完成这项工作,您需要通过更加离散地指定绑定来告诉Binding在哪里寻找属性。
<TextBlock Text="{Binding Name2, Mode=OneWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}" />
这假设您的DataTemplate用于MainWindow类型的对象。玩它来获取你的。
此外,您需要将后面代码中的属性更改为DependencyProperty(因为它是最简单的UIElement。)
public string Name2
{
get { return (string)GetValue(Name2Property); }
set { SetValue(Name2Property, value); }
}
public static readonly DependencyProperty Name2Property =
DependencyProperty.Register(nameof(Name2), typeof(string), typeof(MainWindow));
如果这样做,您的DataTemplate将绑定到该值。
这只是为了回答这个问题并帮助您理解它,而不是我个人如何设计DataTemplate。