如何解决WPF XAML ViewModel与数据网格和列表视图的绑定
这是我要实现的目标的最小工作示例:
XAML:
<Window x:Class="Forms.Wizards.CustomerOrderWizard"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Forms.Wizards"
mc:Ignorable="d">
<Grid>
<DataGrid Name="AssetGrid"
AutoGenerateColumns="False"
HorizontalAlignment="Left"
Height="209" Margin="0,68,0"
VerticalAlignment="Top" Width="793"
Loaded="AssetGrid_Loaded" ItemsSource="{Binding Path=Assets}">
<DataGrid.Columns>
<DataGridTextColumn Header="#" Binding="{Binding Id}" />
<DataGridTemplateColumn Header="Estado">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ListView Margin="10" ItemsSource="{Binding States}">
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock Tag="{Binding Path=Id}" Text="{Binding Path=Name}" FontWeight="Bold" />
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
ViewModel:
public class CustomerOrderViewModel
{
public ObservableCollection<CustomerOrder> Assets { get; set; }
public ObservableCollection<ItemState> States { get; set; }
private ObservableCollection<Customer> Customers { get; set; }
public CustomerOrderViewModel()
{
CustomerOrderService myService = new CustomerOrderService();
CustomerService myCustomerService = new CustomerService();
var assets = myService.GetAllOrders();
var states = myService.GetOrderStates();
var customers = myCustomerService.GetAllCustomers();
States = new ObservableCollection<ItemState>();
Customers = new ObservableCollection<Customer>();
Assets = new ObservableCollection<CustomerOrder>();
foreach (var asset in assets)
{
Assets.Add(asset);
}
foreach (var state in states)
{
States.Add(state);
}
foreach (var customer in customers)
{
Customers.Add(customer);
}
}
}
我的资产已正确加载和绑定(每个客户订单一行),但未显示“状态”和“客户”列表,但它们确实有项目。
我认为绑定列表视图的方式是错误的,但我找不到原因。
解决方法
我必须对ListView对象使用RelativeSource属性来按如下方式检索原始DataContext:
<ListView Margin="10" ItemsSource="{Binding
Path=DataContext.Customers,RelativeSource={RelativeSource AncestorType=Window},Mode=Default}">
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。