绑定代码隐藏中定义的属性和同一模板中类中定义的另一个属性



我想绑定一个在代码隐藏中定义的属性,以及另一个在同一模板中的类中定义的具有数据类型的属性。这里有一个例子:

我的班级:

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中的代码。

我该怎么办?

您应该将第二个TextBlock的数据上下文设置为当前窗口。我认为这可以通过使用像这样的结合表达来实现

<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";
}

我希望这能有所帮助。

尝试以下操作:

在CodeBehind的构造函数中:

public MyView()
{
this.InitializeComponent();
this.DataContext = this;   //set the datacontext here
name2 = "Tim";
}

在XAML中:

<TextBlock Text="{Binding DataContext.name2, ElementName=MyView}"/>

首先,绑定总是首先查看其自身的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。

最新更新