2016-04-18 30 views
0

我正在使用C#,WPF和MVVM開發一個簡單的CRUD。我正在使用DataGrid進行導航,Databounded Textboxes是一個用於插入的「新建」按鈕,用戶可以簡單地更改文本框的值以更改數據,最後單擊「保存」按鈕。在MVVM中插入/編輯時執行操作

現在,我可以在點擊「新建」按鈕後輕鬆禁用DataGrid,並在點擊「保存」按鈕後重新啓用。

但是,版本呢?我想在編輯時禁用DataGrid,但我不知道我在MVVM中如何做。

  1. 我這樣做在視圖中,我從文本框看一些「PropertyChanged」?
  2. 我這樣做是在視圖模型,我也期待一些「的PropertyChanged」從實體屬性(我執行INotifyPropertyChanged我已經實體)?
  3. 另一種選擇?

回答

1

您可以將文本框只讀默認情況下,當用戶進入editcreate new狀態只啓用他們。

順便說一句,你不應該實現CRUD接口時,DataGrid支持了。

編輯:代碼,以幫助您直觀

XAML

<__CONTAINER__.Resources> 
    <Style x:Key="CrudTextBoxStyle" 
      BasedOn="{StaticResource {x:Type TextBox}}" 
      TargetType="TextBox"> 
     <Setter Property="IsEnabled" Value="False" /> 
     <Style.Triggers> 
      <DataTrigger Binding="{Binding EditMode}" Value="CreateNew"> 
       <Setter Property="IsEnabled" Value="True" /> 
      </DataTrigger> 
      <DataTrigger Binding="{Binding EditMode}" Value="Edit"> 
       <Setter Property="IsEnabled" Value="True" /> 
      </DataTrigger> 
     </Style.Triggers> 
    </Style> 
</__CONTAINER__.Resources> 


<DataGrid IsReadOnly="True" 
      ItemsSource="{Binding Records}" 
      SelectedItem="{Binding CurrentRecord}" 
      SelectionMode="Single" 
      SelectionUnit="FullRow" /> 

<Button Content="Create New" /> 
<Button Content="Edit" /> 
<Button Content="Save" /> 
<Button Content="Cancel" /> 

<TextBox Style="{StaticResource CrudTextBoxStyle}" Text="{Binding CurrentRecord.TextProperty1}" /> 
<TextBox Style="{StaticResource CrudTextBoxStyle}" Text="{Binding CurrentRecord.TextProperty2}" /> 

代碼背後

class CrudViewModel 
{ 
    // you should use the full implementation with INPC 
    public Record CurrentRecord { get; set; } 
    public IList<Record> Records { get; set; } 
    public EditMode EditMode { get; set; } 

    private void CreateNewImpl() 
    { 
     CurrentRecord = new Record(); 
     EditMode = EditMode.CreateNew; 
    } 
    private void EditImpl() 
    { 
     EditMode = EditMode.Edit; 
    } 
    private void SaveImpl() 
    { 
     if (EditMode == EditMode.CreateNew) 
     { 
      Records.Add(CurrentRecord); 
     } 

     EditMode = EditMode.View; 
    } 
} 

enum EditMode 
{ 
    View, CreateNew, Edit 
} 
+0

當你說: 「編輯」 或 「新建」 狀態,是從的DbContext? –

+0

不是的。它應該是一個枚舉,你從視圖模型中公開屬性。 – Xiaoy312

+0

我已經添加了一些代碼來幫助您可視化。 – Xiaoy312

相關問題