首页 > 解决方案 > WPF - 绑定到 UserControl 的 PropDP - 在 ItemsControl 的 ItemTemplate 内

问题描述

在 Windows 10 上的 .Net Core 3.1 上的 WPF 中有一个奇怪的数据绑定问题。

我有一个人模型:

public class Person
{
    public long Id { get; set; }
    public string Name { get; set; }
    public long? CityId { get; set; }
}

和这样的城市模型:

public class City
{
    public long Id { get; set; }
    public long ZipCode { get; set; }
    public string Name { get; set; }
}

我有一个这样的 ItemsControl:

<ItemsControl Margin="10" ItemsSource="{Binding People}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Margin="5" Text="{Binding Id}" />
                <TextBlock Margin="5" Text="{Binding Name}" />
                <local:CityView
                    Margin="5"
                    CityId="{Binding CityId}"
                    CityList="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.CityList}" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

我有一个 CityView 用户控件:

<UserControl
x:Class="WpfIssues.CityView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Orientation="Vertical">
    <ComboBox
        DisplayMemberPath="Name"
        ItemsSource="{Binding CityList}"
        SelectedValue="{Binding CityId}"
        SelectedValuePath="Id" />
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="CityId from UserControl CityId PropDp: " />
        <TextBlock FontWeight="Bold" Text="{Binding CityId}" />
    </StackPanel>
</StackPanel>

此用户控件有 2 个 PropDp:

    public long CityId
    {
        get { return (long)GetValue(CityIdProperty); }
        set { SetValue(CityIdProperty, value); }
    }

    public static readonly DependencyProperty CityIdProperty =
        DependencyProperty.Register("CityId", typeof(long), typeof(CityView));

    public List<City> CityList
    {
        get { return (List<City>)GetValue(CityListProperty); }
        set { SetValue(CityListProperty, value); }
    }

    public static readonly DependencyProperty CityListProperty =
        DependencyProperty.Register("CityList", typeof(List<City>), typeof(CityView));

我有一个由包含 ItemsControl 的窗口使用的 ViewModel:

    public List<Person> People { get; set; }
    public List<City> CityList { get; set; }

    public ViewModel()
    {
        People = new List<Person> { new Person {Id = 1, Name = "Thomas", CityId = 1}};
        CityList = new List<City> { new City { Id = 1, Name = "Copenhagen" }};
    }

我的问题是,即使ItemsControls ItemSourceCityId="{Binding CityId}"并且Person具有List<Person>public long? CityId { get; set; }

如果我这样做了,CityId="1"那么 CityView 用户控件会显示CityId Propdp 的值 1

标签: c#wpf.net-coredata-binding

解决方案


推荐阅读