Binding DataTemplate's datacontext property to a usercontrol dependency property

这一生的挚爱 提交于 2021-02-11 08:09:18

问题


In a UWP application, i have a Listview with a datatemplate. The ListView is binded via ItemsSource to an ObservableCollection of my model.

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

Meals is the ObservableCollection of model Meal :

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

Inside ListView DataTemplate, i have a User Control (each element of the ListView have this User control). I want to bind the current meal quantity (Quantity property) to a dependency proeprty of the User control :

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

With User control 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));

But at runtime i have a binding expression error :

Error: BindingExpression path error: 'Quantity' property not found on 'Project.MyUC'

It search on UserControl, but i want to search Quantity property in DataTemplate data context.

I red this post who doesn't help me a lot.

Thanks in advance,

Regards


回答1:


Do not explicitly set a UserControl's DataContext, like you do in the MyUC constructor. Doing so prevents inheriting the DataContext from the parent control of the UserControl.

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

A Binding like

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

expects a property Quantity in the current (inherited) DataContext, which here is the current element in the ItemsSource collection of the ListView. This won't work when you've explicitly set the DataContext.

In the UserControl's XAML, write a Bindings such that it takes the UserControl as its source by specifying the Binding's ElementName property:

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


来源:https://stackoverflow.com/questions/40978136/binding-datatemplates-datacontext-property-to-a-usercontrol-dependency-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!