WPF datagrid中绑定未初始化的ComboBox DataTemplate
我有一个绑定的模型列表和一个DataGrid。值可以是两种数据类型(bool、double) 我的xaml如下所示:WPF datagrid中绑定未初始化的ComboBox DataTemplate,wpf,binding,combobox,datatemplate,Wpf,Binding,Combobox,Datatemplate,我有一个绑定的模型列表和一个DataGrid。值可以是两种数据类型(bool、double) 我的xaml如下所示: <Window.Resources> <comboQuestion:DynamicDataTemplateSelector x:Key="DataTemplateSelector"/> <comboQuestion:BoolToStringConverter x:Key="BoolToStringConverter"/> <
<Window.Resources>
<comboQuestion:DynamicDataTemplateSelector x:Key="DataTemplateSelector"/>
<comboQuestion:BoolToStringConverter x:Key="BoolToStringConverter"/>
</Window.Resources>
<Grid>
<DataGrid Grid.Row="1" Name="signals" AutoGenerateColumns="False" ItemsSource="{Binding}" >
<DataGrid.Resources>
<DataTemplate x:Key="BoolTemplate">
<ComboBox SelectedItem="{Binding Value, Converter={StaticResource BoolToStringConverter}, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
<ComboBoxItem>true</ComboBoxItem>
<ComboBoxItem>false</ComboBoxItem>
</ComboBox>
</DataTemplate>
<DataTemplate x:Key="TextTemplate">
<TextBox Text="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="TextValue" Binding="{Binding Value}"/>
<DataGridTemplateColumn Header="DynamicValue" CellTemplateSelector="{StaticResource DataTemplateSelector}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
但是,行为保持不变。您可以使用以下转换器将布尔值转换为索引号:
public class BooleanToIndexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((bool)value == true) ? 0 : 1;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((int)value == 0) ? true : false;
}
}
然后绑定到组合框上的SelectedIndex:
SelectedIndex="{Binding Value, Converter={StaticResource BooleanToIndexConverter}}
尝试SelectedValue而不是SelectedItem。我已经这样做了:),它的行为方式完全相同,这有点令人惊讶,但事实确实如此。我感觉这是因为转换器返回的是字符串,而不是ComboBoxItem。我会试着想出一个解决方案。然而,我也有同样的怀疑,一旦你开始使用组合键和文本框,很明显,绑定正在工作,而且它正在工作。注意:在你的
转换中,你不应该使用返回((bool)value==true)吗?“真”:“假”代码>?我明白了,这是绝对可能的,但根据我的示例行为,您是否有任何可能的理由?我支持我所说的,我认为它需要转换为ComboBoxItem,但事实是我不知道。在这种情况下,此解决方案应该很适合您。我必须进一步研究组合框转换器。
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var cbi = new ComboBoxItem();
cbi.Content = ((bool)value == true) ? "true" : "false";
return cbi;
}
public class BooleanToIndexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((bool)value == true) ? 0 : 1;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((int)value == 0) ? true : false;
}
}
SelectedIndex="{Binding Value, Converter={StaticResource BooleanToIndexConverter}}