2012-05-02 43 views
4

我有這三個屬性一個ViewModel:應該在哪裏「調用命令屬性更改」功能去?

string searchString; 
ObservableCollection<Company> ListedItems; 
ICommand SearchCommand; 

它代表公司的在我的數據庫搜索列表。 SearchCommand根據searchString的值搜索數據庫,然後用結果填充ListedItems

SearchString綁定到文本框,而SearchCommand綁定到按鈕。我想這樣做,當用戶鍵入文本框時,SearchCommand會自動執行,用戶不必點擊按鈕。

此刻,我通過我的ViewModel做到這一點:

public ListViewModel() { 
    this.PropertyChanged += delegate(object o, PropertyChangedEventArgs e) 
    { 
     if (e.PropertyName == "SearchString") 
      SearchCommand.Execute(null); 
    }; 
} 

這是正確的嗎?在視圖中使用這個功能會更好嗎?如果是這樣,那是如何實現的?

回答

2

在我看來,更合適的解決方案是從ViewModel的SearchString屬性的setter調用該命令。

+0

掛鉤到PropertyChanged更方便,因爲它只發生在屬性更改(而不是設置爲相同的值)時也在真實viewModel中有幾個不同的字符串屬性被搜索。 – Oliver

+0

@Oliver在setter中,你可以做'if(myProperty == value){return; }'。這樣,你避免了「設置爲相同的值」(並且在我看來,當值沒有改變時,你不應該觸發任何propertyChanged事件) – Default

1

將綁定命令更好地綁定到TextBox。可能this將會有幫助。

1

我個人會考慮使用Expression Blend SDK InvokeCommandAction

我敲了一個工作的例子。下面是這個視圖:

<Window 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" x:Class="WpfApplication1.MainWindow" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <StackPanel> 
      <TextBox Text="Hello World"> 
       <i:Interaction.Triggers> 
        <i:EventTrigger EventName="TextChanged"> 
         <i:InvokeCommandAction Command="{Binding DoItCommand}" /> 
        </i:EventTrigger> 
       </i:Interaction.Triggers> 
      </TextBox> 
      <Button x:Name="CommandButton" Command="{Binding DoItCommand}" Content="Click me" /> 
     </StackPanel> 
    </Grid> 
</Window> 

和一個非常簡單的視圖模型(使用PRISM的​​):

public class SomeViewModel 
    { 
     public SomeViewModel() 
     { 
      DoItCommand = new DelegateCommand(() => Debug.WriteLine("It Worked")); 
     } 

     public ICommand DoItCommand { get; private set; } 
    } 

簡單的電線連接起來後面的代碼視圖模型:

public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      DataContext = new SomeViewModel(); 
     } 
    } 

你不」 t需要有Expression Blend來做到這一點 - SDK是free to download並使用。

如果你不喜歡使用Expression Blend SDK,MVVM Light提供了類似的EventToCommand。

當然,如果仍然有理由讓按鈕就位(或者您希望利用該命令的可執行邏輯),那麼這樣做纔有意義,否則您可以在setter中關閉屬性。