C# Wpf多个组合框绑定到一个属性
我有一个数据网格,其中一个单元格是一个组合框,如:C# Wpf多个组合框绑定到一个属性,c#,wpf,combobox,C#,Wpf,Combobox,我有一个数据网格,其中一个单元格是一个组合框,如: <DataGrid x:Name="Applications" RowStyle="{StaticResource CollapsedRow}" AutoGenerateColumns="false" CanUserAddRows="false" ItemsSource="{Binding Applications}"> <DataGrid.Columns> <DataGridTemplateColumn
<DataGrid x:Name="Applications" RowStyle="{StaticResource CollapsedRow}" AutoGenerateColumns="false" CanUserAddRows="false" ItemsSource="{Binding Applications}">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content='˅' FontSize="9" Name="ExpanderButton" Click="OnGroupChange" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Width="181" Header="Name" Binding="{Binding Name, Mode=OneWay}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=DataContext.Cabins,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"
SelectedValuePath="Id" IsSynchronizedWithCurrentItem="True"
SelectedValue="{Binding Path=DataContext.SelectedCabin,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
mah:TextBoxHelper.Watermark="{Binding Path=DataContext.CabinsWatermark, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"
Height="2" Width="300" Margin="10 5 10 10" HorizontalAlignment="Left">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource GuidConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
现在的问题是,当我在组合框中选择项时,我得到的不是单个值,而是两个值。我假设我选择的一个组合框中有所有值,以确保我用后面的测试代码进行了双重检查:
private void ComboBox_OnSelectCabinChanged(object sender, RoutedEventArgs e)
{
var combo = (ComboBox)sender;
if (combo != null && combo.IsDropDownOpen)
{
((ApplicationsViewModel)DataContext).SelectedCabin = (Guid?)sender;
combo.IsDropDownOpen = false;
}
}
我在这里和组合框项目列表和铸造例外。造成这种情况的根本原因是什么?是否有办法将多个组合框值绑定到一个属性,因此我选择一个组合框,它将覆盖另一个组合框。看起来您正在将所有行详细信息组合框的SelectedValue绑定到同一个源属性。并且不能将发送方参数强制转换为Guid?。尝试强制转换组合框的SelectedValue属性:
如果不想在视图中处理SelectionChanged事件,可以使用交互触发器来执行设置源属性的命令。有关此操作的详细信息,请参阅。似乎您正在将所有行详细信息组合框的SelectedValue绑定到同一个源属性。并且不能将发送方参数强制转换为Guid?。尝试强制转换组合框的SelectedValue属性:SelectedCabin=Guid?combo.SelectedValue;。我知道这是一件微不足道的事情,它很有效:现在我要尝试在没有代码隐藏的情况下完成它,这是可能的。你可以使用一个交互触发器。请看我的答案。
private void ComboBox_OnSelectCabinChanged(object sender, RoutedEventArgs e)
{
var combo = (ComboBox)sender;
if (combo != null && combo.IsDropDownOpen)
{
((ApplicationsViewModel)DataContext).SelectedCabin = (Guid?)sender;
combo.IsDropDownOpen = false;
}
}
SelectedCabin = (Guid?)combo.SelectedValue;