c# - 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 ItemSource是CityId="{Binding CityId}"
并且Person类具有List<Person>
public long? CityId { get; set; }
如果我这样做了,CityId="1"
那么 CityView 用户控件会显示CityId Propdp 的值 1
解决方案
推荐阅读
- airflow - 如何从 SimpleHttpOperator 读取响应正文
- acumatica - 如何更正来自 Acuminator 的 PX1011 警告?(它建议密封类,但这会导致错误列表中的错误)
- javascript - THREE.js WebGLRenderer 画布消耗“点击”鼠标事件
- node.js - Nodejs逐行读取文件并将结果累积到全局对象中
- r - 在 Svydesign 对象中按十分位数计算平均值
- excel - 如果一个保留一个,如果更高,则在 Excel 中给出 2
- javascript - 为什么 javascript IF/ELSE 不能正常工作?
- cmd - 有没有办法在 Wix 项目中指定命令行别名?
- xaml - UWP 偏移 GridView 滚动条
- sql - 如何修复我的桌子以使其正常工作?