【问题标题】:Cannot edit members in WPF DataGrid DataGridTextColumn无法编辑 WPF DataGrid DataGridTextColumn 中的成员
【发布时间】:2016-02-07 17:48:46
【问题描述】:

我正在开发一个小型 WPF 应用程序,我想向用户提供一个字符串列表,用户可以对其进行编辑、添加或删除。

我做的第一件事是创建一个带有视图模型更改通知的基类:

  public abstract class BaseViewModel : INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
    {
      this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
  }

在此之后,我为绑定/更改通知的字符串创建了一个包装器:

  public class StringViewModel : BaseViewModel
  {
    private string value;

    public string Value
    {
      get { return this.value; }
      set
      {
        if (value == this.value) return;
        this.value = value;
        this.RaisePropertyChanged(nameof(this.Value));
      }
    }
  }

然后我有一个使用这个类的视图模型(我省略了其他不相关的成员):

  public class UserSettingsDataViewModel : BaseViewModel
  {
    private ObservableCollection<StringViewModel> blacklistedFiles;

    public ObservableCollection<StringViewModel> BlacklistedFiles
    {
      get { return this.blacklistedFiles; }
      set
      {
        if (Equals(value, this.blacklistedFiles)) return;
        this.blacklistedFiles = value;
        this.RaisePropertyChanged(nameof(this.BlacklistedFiles));
      }
    }
  }

最后,我将这个包含在我的 XAML 中,用于相关屏幕:

<WrapPanel>
  <Label>Blacklisted files</Label>
  <DataGrid ItemsSource="{Binding Data.BlacklistedFiles}" AutoGenerateColumns="False">
    <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding Value}" Header="File name" />
      <DataGridTemplateColumn Header="Remove">
        <DataGridTemplateColumn.CellTemplate>
          <DataTemplate>
            <Button Content="Remove" Command="Delete" />
          </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    </DataGrid.Columns>
  </DataGrid>
</WrapPanel>

一切正常,除了我无法编辑新成员或现有成员的值。我可以点击单元格并让它进入编辑模式模式,但是按键没有任何作用(除了我似乎能够添加或删除空格)。我觉得必须有一个直截了当的解决方法,但它让我望而却步。

【问题讨论】:

    标签: c# wpf xaml datagrid


    【解决方案1】:

    事实证明,这是因为此 WPF 表单存在于 Windows 窗体应用程序中。解决的步骤是:

    • 添加对 WindowsFormsIntegration 库的引用。

    • 在创建窗口的类中,添加using语句using Systems.Windows.Forms.Integration

    • 在窗口拨打ElementHost.EnableModelessKeyboardInterop

    我必须感谢this answer,这有助于我找出问题所在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-28
      • 2012-11-03
      • 2011-08-23
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 2013-07-30
      相关资源
      最近更新 更多