【问题标题】:Binding DataTemplate's datacontext property to a usercontrol dependency property将 DataTemplate 的 datacontext 属性绑定到 usercontrol 依赖属性
【发布时间】:2016-12-05 15:52:03
【问题描述】:

在 UWP 应用程序中,我有一个带有数据模板的 Listview。 ListView 通过 ItemsSource 绑定到我的模型的 ObservableCollection。

<ListView SelectionMode="None"
              ItemTemplate="{StaticResource MydataTemplate}"
              ItemsSource="{Binding Meals, Mode=OneWay}"

Meals 是模型 Meal 的 ObservableCollection:

public class Meal
{
    public string restaurantId { get; set; }
    public double price { get; set; }
    public int Quantity { get; set; } = 0;
}

在 ListView DataTemplate 中,我有一个用户控件(ListView 的每个元素都有这个用户控件)。我想将当前的膳食数量(数量属性)绑定到用户控件的依赖属性:

<DataTemplate x:Key="mydataTemplate">
    ...
    <ccontrol:MyUC Value="{Binding Quantity, Mode=TwoWay}" Grid.Column="2" />
    ...
</DataTemplate>

使用用户控制 DP:

public sealed partial class MyUC : UserControl
{
    public MyUC()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }

    public int Value
    {
        get { return (int)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Value.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(int), typeof(ResaNumUpDown), new PropertyMetadata(0));

但在运行时我有一个绑定表达式错误:

错误:BindingExpression 路径错误:在“Project.MyUC”上找不到“Quantity”属性

它在 UserControl 上搜索,但我想在 DataTemplate 数据上下文中搜索 Quantity 属性。

我红了this post谁帮不了我很多。

提前致谢,

问候

【问题讨论】:

    标签: uwp uwp-xaml


    【解决方案1】:

    不要像在MyUC 构造函数中那样显式设置用户控件的DataContext。这样做可以防止从 UserControl 的父控件继承 DataContext。

    public MyUC()
    {
        this.InitializeComponent();
        // this.DataContext = this; // remove this line
    }
    

    类似的绑定

    <ccontrol:MyUC Value="{Binding Quantity}" />
    

    在当前(继承的)DataContext 中需要一个属性Quantity,这里是ListView 的ItemsSource 集合中的当前元素。当您明确设置 DataContext 时,这将不起作用。

    在 UserControl 的 XAML 中,通过指定 Binding 的 ElementName 属性,编写一个 Bindings 以将 UserControl 作为其源:

    <UserControl ... x:Name="self">
       ...
       <TextBlock Text="{Binding Value, ElementName=self}" />
       ...
    </UserControl>
    

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 2011-07-29
      • 2014-08-31
      • 2010-12-27
      相关资源
      最近更新 更多