【发布时间】:2016-12-23 10:14:13
【问题描述】:
我有一个绑定到单独 ItemsSource 的 DataGridTemplateColumn 组合框似乎通过将此组合框绑定到另一个源它会更改 DataContext。
所以我在将组合框中所选项目的值绑定到 DataGrid 中所选行的 DataContext 时遇到问题。
XAML:
<DataGrid HorizontalAlignment="Left" ItemsSource="{Binding Path=WorldDataList}" SelectedItem="{Binding SelectedWorldData}">
<DataGridTemplateColumn Header="Country" >
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type StackPanel}},Path=DataContext.Countries}"
SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=SelectedItem.Country}"
SelectedIndex="0"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid>
C#:
class WorldDataViewModel : ObservableObject
{
private ObservableCollection<WorldData> _worldDataList = new ObservableCollection<WorldData>();
public ObservableCollection<WorldData> WorldDataList
{
get { return _worldDataList; }
set
{
Set(ref _worldDataList, value);
}
}
public List<string> Countries {get;set;}
private WorldData worldData;
private WorldData SelectedWorldData
{
get{return worldData;}
set
{
Set(ref worldData, value);
}
}
}
class WorldData : ObservableObject
{
private string country;
public string Country
{
get{return country;}
set
{
Set(ref country, value);
}
}
我得到了例外:
System.Windows.Data 错误:23:无法转换“{NewItemPlaceholder}” 从“NamedObject”类型到“en-US”文化类型“WorldData” 默认转换;考虑使用 Binding 的 Converter 属性。 NotSupportedException:'System.NotSupportedException: TypeConverter 无法从 MS.Internal.NamedObject 转换。在 System.ComponentModel.TypeConverter.GetConvertFromException(对象 值)在 System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext 上下文,CultureInfo 文化,对象值)在 MS.Internal.Data.DefaultValueConverter.ConvertHelper(对象 o,类型 destinationType、DependencyObject targetElement、CultureInfo 文化、 Boolean isForward)' 抛出异常:'System.NotSupportedException' 在 PresentationFramework.dll 中
似乎我应该使用类型转换器,但似乎我不应该这样做,因为我在 SO 上找到的很少
我想现在我将放弃并为组合框添加一个单独的框并绑定到 Datagrid 的选定项。我不觉得它很直观,所以如果你有任何聪明的想法,请。
【问题讨论】:
标签: c# .net wpf combobox datagrid