2015-10-06 171 views
-1

这是一个展示我遇到问题的行为的示例。我有一个数据网格绑定到viewmodel中的可观察的记录集合。在DataGrid中,我有一个DataGridTemplateColumn,它包含一个从viewmodel中的列表填充的组合框。该数据网格还包含文本列。窗口底部有一些文本框来显示记录内容​​。DataGrid中的WPF组合框

<Window x:Class="Customer.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:Customer" 
    Title="MainWindow" Height="350" Width="525"> 

    <Window.Resources> 
     <local:SelectedRowConverter x:Key="selectedRowConverter"/> 
    </Window.Resources> 
    <Grid> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="8*"/> 
      <RowDefinition Height="3*"/> 
     </Grid.RowDefinitions> 
     <DataGrid x:Name="dgCustomers" AutoGenerateColumns="False" 
        ItemsSource="{Binding customers}" SelectedItem="{Binding SelectedRow, 
        Converter={StaticResource selectedRowConverter}, Mode=TwoWay}" 
        CanUserAddRows="True" Grid.Row="0" > 
      <DataGrid.Columns> 
       <DataGridTemplateColumn Width="Auto" Header="Country"> 
        <DataGridTemplateColumn.CellTemplate> 
         <DataTemplate> 
          <ComboBox x:Name="cmbCountry" ItemsSource="{Binding DataContext.countries, 
           RelativeSource={RelativeSource AncestorType={x:Type Window}}}" 
             DisplayMemberPath="name" SelectedValuePath="name" Margin="5" 
             SelectedItem="{Binding DataContext.SelectedCountry, 
           RelativeSource={RelativeSource AncestorType={x:Type Window}}, Mode=TwoWay, 
           UpdateSourceTrigger=PropertyChanged}" SelectionChanged="cmbCountry_SelectionChanged" /> 
         </DataTemplate> 
        </DataGridTemplateColumn.CellTemplate> 
       </DataGridTemplateColumn> 
       <DataGridTextColumn Header="Name" Binding="{Binding name}" Width="1*"/> 
       <DataGridTextColumn Header="Phone" Binding="{Binding phone}" Width="1*"/> 
      </DataGrid.Columns> 
     </DataGrid> 

     <Grid x:Name="grdDisplay" DataContext="{Binding ElementName=dgCustomers}" Grid.Row="1"> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="1*"/> 
       <ColumnDefinition Width="1*"/> 
       <ColumnDefinition Width="1*"/> 
      </Grid.ColumnDefinitions> 
      <Label Grid.Column="2" Content="Country:" VerticalAlignment="Center" HorizontalAlignment="Right"/> 
      <Label Grid.Column="4" Content="Code:" VerticalAlignment="Center" HorizontalAlignment="Right"/> 
      <BulletDecorator Grid.Column="0"> 
       <BulletDecorator.Bullet> 
        <Label Content="Name:" VerticalAlignment="Center" HorizontalAlignment="Right"/> 
       </BulletDecorator.Bullet> 
       <TextBox x:Name="txtId" Text="{Binding ElementName=dgCustomers, Path=SelectedItem.name}" Margin="5,5,5,5"/> 
      </BulletDecorator> 
      <BulletDecorator Grid.Column="1"> 
       <BulletDecorator.Bullet> 
        <Label Content="Code:" VerticalAlignment="Center" HorizontalAlignment="Right"/> 
       </BulletDecorator.Bullet> 
       <TextBox x:Name="txtCode" Text="{Binding ElementName=dgCustomers, Path=SelectedItem.countryCode}" Margin="5,5,5,5"/> 
      </BulletDecorator> 
      <BulletDecorator Grid.Column="2"> 
       <BulletDecorator.Bullet> 
        <Label Content="Phone:" VerticalAlignment="Center" HorizontalAlignment="Right"/> 
       </BulletDecorator.Bullet> 
       <TextBox x:Name="txtPhone" Text="{Binding ElementName=dgCustomers, Path=SelectedItem.phone}" Margin="5,5,5,5"/> 
      </BulletDecorator> 
     </Grid> 
    </Grid> 
</Window> 

最初没有记录,因此数据网格是空的,仅显示一个包含组合框线。如果用户首先将数据输入到文本列中,则将记录添加到该集合,并且可以将组合框值添加到记录中。但是,如果用户首先选择组合框值,那么当另一列被选中时,该值将消失。如果首先选择将组合框数据添加到记录中,如何获取?

代码隐藏:

public partial class MainWindow : Window 
{ 
    public GridModel gridModel { get; set; } 

    public MainWindow() 
    { 
     InitializeComponent(); 
     gridModel = new GridModel(); 
     //dgCustomers.DataContext = gridModel; 
     this.DataContext = gridModel; 
    } 

    private void cmbCountry_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     ComboBox c = sender as ComboBox; 
     Debug.Print("ComboBox selection changed, index is " + c.SelectedIndex + ", selected item is " + c.SelectedItem); 
    } 
} 

备案类:

public class Record : ViewModelBase 
{ 
    private string _name; 
    public string name 
    { 
     get { return _name; } 
     set 
     { 
      _name = value; 
      OnPropertyChanged("name"); 
     } 
    } 

    private string _phone; 
    public string phone 
    { 
     get { return _phone; } 
     set 
     { 
      _phone = value; 
      OnPropertyChanged("phone"); 
     } 
    } 

    private int _countryCode; 
    public int countryCode 
    { 
     get { return _countryCode; } 
     set 
     { 
      _countryCode = value; 
      OnPropertyChanged("countryCode"); 
     } 
    } 
} 

国家类:

public class Country : ViewModelBase 
{ 
    private string _name; 
    public string name 
    { 
     get { return _name; } 
     set 
     { 
      _name = value; 
      OnPropertyChanged("name"); 
     } 
    } 

    private int _id; 
    public int id 
    { 
     get { return _id; } 
     set 
     { 
      _id = value; 
      OnPropertyChanged("id"); 
     } 
    } 

    private int _code; 
    public int code 
    { 
     get { return _code; } 
     set 
     { 
      _code = value; 
      OnPropertyChanged("code"); 
     } 
    } 

    public override string ToString() 
    { 
     return _name; 
    } 
} 

GridModel:

public class GridModel : ViewModelBase 
{ 
    public ObservableCollection<Record> customers { get; set; } 
    public List<Country> countries { get; set; } 
    public GridModel() 
    { 
     customers = new ObservableCollection<Record>(); 
     countries = new List<Country> { new Country { id = 1, name = "England", code = 44 }, new Country { id = 2, name = "Germany", code = 49 }, 
     new Country { id = 3, name = "US", code = 1}, new Country { id = 4, name = "Canada", code = 11 }}; 
    } 

    private Country _selectedCountry; 
    public Country SelectedCountry 
    { 
     get 
     { 
      return _selectedCountry; 
     } 
     set 
     { 
      _selectedCountry = value; 
      _selectedRow.countryCode = _selectedCountry.code; 
      OnPropertyChanged("SelectedRow"); 
     } 
    } 

    private Record _selectedRow; 
    public Record SelectedRow 
    { 
     get 
     { 
      return _selectedRow; 
     } 
     set 
     { 
      _selectedRow = value; 
      Debug.Print("Datagrid selection changed"); 
      OnPropertyChanged("SelectedRow"); 
     } 
    } 
} 

转换器:

class Converters 
{ 
} 

public class SelectedRowConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return value; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value is Record) 
      return value; 
     return new Customer.Record(); 
    } 
} 

ViewModelBase:

public class ViewModelBase : INotifyPropertyChanged 
{ 
    public ViewModelBase() 
    { 

    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    public void OnPropertyChanged(string name) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(name)); 
     } 
    } 
} 

感谢您的帮助!

编辑感谢您的帮助马克,我跑,你在下面你的答案提供的代码,但我仍然不能在窗口底部得到的文本框中国家代码。我得到这些错误:

System.Windows.Data Error: 23 : Cannot convert '{NewItemPlaceholder}' from type 'NamedObject' to type 'CustomersFreezable.RecordViewModel' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: TypeConverter cannot convert from MS.Internal.NamedObject. at System.ComponentModel.TypeConverter.GetConvertFromException(Object value) at System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)'

System.Windows.Data Error: 7 : ConvertBack cannot convert value '{NewItemPlaceholder}' (type 'NamedObject'). BindingExpression:Path=SelectedRow; DataItem='GridModel' (HashCode=62992796); target element is 'DataGrid' (Name='dgCustomers'); target property is 'SelectedItem' (type 'Object') NotSupportedException:'System.NotSupportedException: TypeConverter cannot convert from MS.Internal.NamedObject. at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward) at MS.Internal.Data.ObjectTargetConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture) at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)' Datagrid selection changed Datagrid selection changed

System.Windows.Data Error: 40 : BindingExpression path error: 'countryCode' property not found on 'object' ''RecordViewModel' (HashCode=47081572)'. BindingExpression:Path=SelectedItem.countryCode; DataItem='DataGrid' (Name='dgCustomers'); target element is 'TextBox' (Name='txtCode'); target property is 'Text' (type 'String')

System.Windows.Data Error: 23 : Cannot convert '{NewItemPlaceholder}' from type 'NamedObject' to type 'CustomersFreezable.RecordViewModel' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: TypeConverter cannot convert from MS.Internal.NamedObject. at System.ComponentModel.TypeConverter.GetConvertFromException(Object value) at System.ComponentModel.TypeConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward)'

System.Windows.Data Error: 7 : ConvertBack cannot convert value '{NewItemPlaceholder}' (type 'NamedObject'). BindingExpression:Path=SelectedRow; DataItem='GridModel' (HashCode=62992796); target element is 'DataGrid' (Name='dgCustomers'); target property is 'SelectedItem' (type 'Object') NotSupportedException:'System.NotSupportedException: TypeConverter cannot convert from MS.Internal.NamedObject. at MS.Internal.Data.DefaultValueConverter.ConvertHelper(Object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, Boolean isForward) at MS.Internal.Data.ObjectTargetConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture) at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)' Datagrid selection changed

System.Windows.Data Error: 40 : BindingExpression path error: 'countryCode' property not found on 'object' ''RecordViewModel' (HashCode=47081572)'. BindingExpression:Path=SelectedItem.countryCode; DataItem='DataGrid' (Name='dgCustomers'); target element is 'TextBox' (Name='txtCode'); target property is 'Text' (type 'String')

我试图通过改变静态资源,解决BindingExpression路径错误:

<local:BindingProxy x:Key="CountryProxy" Data="{Binding}" /> 

,因此DataGrid的ItemsSource时:

ItemsSource="{Binding Source={StaticResource ResourceKey=CountryProxy}, Path=Data.countries}" DisplayMemberPath="name" 

和文本框的绑定:

<TextBox x:Name="txtCode" Text="{Binding Path=record.countryCode}" Margin="5,5,5,5"/> 

这摆脱了错误40,但仍然没有看到文本框中的任何东西。你能告诉我什么是错的吗?

回答

3

请原谅我的诚实,但这段代码有很多错误。

首先,MVVM存在一些严重的偏差。 MVVM是一个分层架构......首先是模型,然后是视图模型顶部,然后是视图顶部。转换器在技术上是视图的一部分,但如果它们位于视图的另一侧,则与视图模型相比。

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
{ 
    if (value is Record) 
     return value; 
    return new Customer.Record(); <<<<<<<< this here 
} 

你有转换器直接与非视图类的工作是一个很好的迹象,您的视图模式”不是个任何时候:你在做什么使用转换器来产生什么有效的应该是你的模型新纪录是正确地完成工作,并且它几乎总是会导致破坏的绑定和错误行为。

另一个问题是,你的Record类看起来像它的意图是模型,即因为它有一个国家的整数代码,而不是对Country类实例的引用。然而,这个类是从ViewModelBase中派生出来的,并且会执行属性更改通知。此外,类型为Country的一个字段(即GridModel中的SelectedCountry)将被所有记录绑定,因此将国家代码更改为一个可以更改它们!

要回答您的具体问题,但问题是DataGrid不会创建新记录,直到它检测到其中一个字段已被编辑。在这种情况下,您与SelectedRow的绑定不在记录本身中,因此记录没有被创建,并且该值没有被传播。

这里有一个固定的版本,坚持MVVM好一点,并修复了绑定的问题:

// record model 
public class Record 
{ 
    public string name {get; set;} 
    public string phone { get; set; } 
    public int countryCode {get; set;} 
} 

// record view model 
public class RecordViewModel : ViewModelBase 
{ 
    private Record record = new Record(); 

    public string name 
    { 
     get { return record.name; } 
     set 
     { 
      record.name = value; 
      RaisePropertyChanged("name"); 
     } 
    } 

    public string phone 
    { 
     get { return record.phone; } 
     set 
     { 
      record.phone = value; 
      RaisePropertyChanged("phone"); 
     } 
    } 

    private Country _country; 
    public Country country 
    { 
     get { return _country; } 
     set 
     { 
      _country = value; 
      record.countryCode = value.code; 
      RaisePropertyChanged("country"); 
     } 
    } 

} 

public class Country : ViewModelBase 
{ 
    private string _name; 
    public string name 
    { 
     get { return _name; } 
     set 
     { 
      _name = value; 
      RaisePropertyChanged("name"); 
     } 
    } 

    private int _id; 
    public int id 
    { 
     get { return _id; } 
     set 
     { 
      _id = value; 
      RaisePropertyChanged("id"); 
     } 
    } 

    private int _code; 
    public int code 
    { 
     get { return _code; } 
     set 
     { 
      _code = value; 
      RaisePropertyChanged("code"); 
     } 
    } 

    public override string ToString() 
    { 
     return _name; 
    } 
} 

public class GridModel : ViewModelBase 
{ 
    public ObservableCollection<RecordViewModel> customers { get; set; } 
    public List<Country> countries { get; set; } 

    public GridModel() 
    { 
     customers = new ObservableCollection<RecordViewModel>(); 
     countries = new List<Country> { new Country { id = 1, name = "England", code = 44 }, new Country { id = 2, name = "Germany", code = 49 }, 
    new Country { id = 3, name = "US", code = 1}, new Country { id = 4, name = "Canada", code = 11 }}; 
    } 

    private RecordViewModel _selectedRow; 
    public RecordViewModel SelectedRow 
    { 
     get 
     { 
      return _selectedRow; 
     } 
     set 
     { 
      _selectedRow = value; 
      Debug.Print("Datagrid selection changed"); 
      RaisePropertyChanged("SelectedRow"); 
     } 
    } 
} 

// this is needed for when you need to bind something that isn't part of the visual tree (i.e. your combobox dropdowns) 
// see http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/ for details 
public class BindingProxy : Freezable 
{ 
    #region Overrides of Freezable 

    protected override Freezable CreateInstanceCore() 
    { 
     return new BindingProxy(); 
    } 

    #endregion 

    public object Data 
    { 
     get { return (object)GetValue(DataProperty); } 
     set { SetValue(DataProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty DataProperty = 
     DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null)); 
} 

而XAML:

<Window.Resources> 
    <local:BindingProxy x:Key="CountryProxy" Data="{Binding Path=countries}" /> 
</Window.Resources> 

<Grid> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="8*"/> 
     <RowDefinition Height="3*"/> 
    </Grid.RowDefinitions> 
    <DataGrid x:Name="dgCustomers" AutoGenerateColumns="False" 
      ItemsSource="{Binding customers}" SelectedItem="{Binding SelectedRow, Mode=TwoWay}" 
      CanUserAddRows="True" Grid.Row="0" > 
     <DataGrid.Columns> 
      <DataGridComboBoxColumn Header="Country" 
       ItemsSource="{Binding Source={StaticResource ResourceKey=CountryProxy}, Path=Data}" DisplayMemberPath="name" 
       SelectedItemBinding="{Binding country, UpdateSourceTrigger=PropertyChanged}" /> 
      <DataGridTextColumn Header="Name" Binding="{Binding name, UpdateSourceTrigger=PropertyChanged}" Width="1*" /> 
      <DataGridTextColumn Header="Phone" Binding="{Binding phone, UpdateSourceTrigger=PropertyChanged}" Width="1*"/> 
     </DataGrid.Columns> 
    </DataGrid> 

    <Grid x:Name="grdDisplay" Grid.Row="1"> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="1*"/> 
      <ColumnDefinition Width="1*"/> 
      <ColumnDefinition Width="1*"/> 
     </Grid.ColumnDefinitions> 
     <Label Grid.Column="2" Content="Country:" VerticalAlignment="Center" HorizontalAlignment="Right"/> 
     <Label Grid.Column="4" Content="Code:" VerticalAlignment="Center" HorizontalAlignment="Right"/> 
     <BulletDecorator Grid.Column="0"> 
      <BulletDecorator.Bullet> 
       <Label Content="Name:" VerticalAlignment="Center" HorizontalAlignment="Right"/> 
      </BulletDecorator.Bullet> 
      <TextBox x:Name="txtId" Text="{Binding Path=SelectedRow.name}" Margin="5,5,5,5"/> 
     </BulletDecorator> 
     <BulletDecorator Grid.Column="1"> 
      <BulletDecorator.Bullet> 
       <Label Content="Code:" VerticalAlignment="Center" HorizontalAlignment="Right"/> 
      </BulletDecorator.Bullet> 
      <TextBox x:Name="txtCode" Text="{Binding Path=SelectedRow.country.code}" Margin="5,5,5,5"/> 
     </BulletDecorator> 
     <BulletDecorator Grid.Column="2"> 
      <BulletDecorator.Bullet> 
       <Label Content="Phone:" VerticalAlignment="Center" HorizontalAlignment="Right"/> 
      </BulletDecorator.Bullet> 
      <TextBox x:Name="txtPhone" Text="{Binding Path=SelectedRow.phone}" Margin="5,5,5,5"/> 
     </BulletDecorator> 
    </Grid> 
</Grid> 

忘记转换器,你不需要它。这段代码确实介绍的一个问题是,您现在需要点击组合框两次:首先选择该行,然后再次编辑它。但网络周围有很多地方显示如何解决这个问题,所以我会把它留给你。

+0

任何批评,当它是如此有建设性:)赞赏我运行您发送的代码,但仍然没有看到窗口底部的文本框中的countryCode。输出窗口中有几个错误;我编辑了这个问题来添加它们。 –

+0

对不起,国家代码的绑定不正确,我在上面的XAML中修复了它。我注意到的另一件事是底部的那些字段直接绑定到元素。虽然这通常起作用,但如果绑定到视图模型字段(现在我已更改该代码执行),您会发现在问题的路上遇到的问题更少,特别是如果您开始移动XAML或者如果您需要在代码中添加断点以确保控件正常工作。 –

+0

最后一件事......底部的国家/地区代码编辑字段目前正确显示国家/地区代码,但编辑它不会传播回记录,这基本上是在数据网格中使用组合框的一个副作用,但国家代码如下。如果你确实需要这个功能,那么你需要添加一个countryCode字段到视图模型。这引发了视图模型如何首先获得国家数组......这可以通过让GridModel监视将新的RecordViewModel添加到ObservableCollection并在创建它们时初始化它们来完成。 –