【发布时间】:2014-05-01 21:08:39
【问题描述】:
对我的要求有一点烦人的问题,希望可以解决。
假设您有以下类:
public class Foo
{
public string Name { get; set; }
public List<FooB> FooBs { get; set; }
}
public class FooB
{
public int Id1 { get; set; }
public int Id2 { get; set; }
public decimal Sum { get; set; }
}
现在Foo 类有一个FooB 列表,其中包含给定Id1 和Id2 值和一个Sum 计算值。
在我的 WPF 用户界面中,我有 2 ComboBoxes 和 1 DataGrid。
1 个 ComboBox 包含有关 Id1 的信息,另一个包含有关 Id2 的信息。
现在在我的 DataGrid 中,我有一个 Foo 列表,其中显示了 2 列,其中一个显然是名称,但另一个现在让我很头疼。
第二列应显示"correct" FooB 类的Sum 属性。
正确的 FooB 类由 UI 中的 2 个 ComboBox 和 SelectedItem 确定。
到目前为止,我所做的是在我的 CodeBehind 中创建 2 个属性:(请注意,它们实际上有支持字段和 PropertyChanged 指定我将代码简化为我的主要问题)
public int SelectedId1 { get; set; }
public int SelectedId2 { get; set; }
这两个属性绑定到对应的ComboBox:
<c1:C1ComboBox ItemsSource="{Binding Id1s}"
SelectedItem="{Binding SelectedId1}" />
<c1:C1ComboBox ItemsSource="{Binding Id2s}"
SelectedItem="{Binding SelectedId2}" />
到目前为止,我的 DataGrid 如下所示:
<local:BindingProxy x:Key="BindingProxy"
Data="{Binding}" />
<DataGrid ItemsSource={Bindings Foos}>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" />
<DataGridTextColumn>
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource GetCorrectFooB}">
<Binding Binding="."></Binding>
<Binding Binding="Data.SelectedId1"></Binding>
<Binding Binding="Data.SelectedId2"></Binding>
</MultiBinding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
(请注意 BindingProxy 来自此处:http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/ - 以启用从 DataGridRow 的 DataContext 中的窗口获取数据)
转换器如下所示:
public class GetCorrectFooB : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var foo = (Foo)values[0];
var id1 = (int) values[1];
var id2 = (int) values[2];
return foo.FooBs.First(x => x.Id1 == id1 && x.Id2 == id2).Sum;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
这目前工作得很好,甚至当我在 UI 中更改 2 个 ComboBoxes 中的值并相应地更新信息时表现正确但是......当底层 Sum PropertyChanges 并且收到 PropertyChanges 的通知时,UI 没有更新。
如果我只是将列绑定到它,它工作正常
<DataGridTextColumn Binding="{Binding FooBs[12].Sum}" />
你可以想象我不想在那里有一个索引,因为我需要通过 UI 中的 ComboBoxes 来更新它。
希望你能帮帮我。
【问题讨论】:
标签: c# wpf datagrid combobox multibinding