4

次の 3 つのプロパティを持つ viewModel があります。

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

これは、データベース内の会社の検索可能なリストを表しています。SearchCommandの値に基づいてデータベースを検索し、結果searchStringを取り込みListedItemsます。

SearchStringSearchCommandボタンにバインドされている間、テキストボックスにバインドされています。SearchCommandユーザーがテキストボックスに入力すると、ユーザーがボタンをクリックしなくても自動的に実行されるようにしたいと考えています。

現時点では、viewModel を介してこれを行います。

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

これは正しいです?この機能をビューに含めた方がよいでしょうか? もしそうなら、それはどのように達成されますか?

4

3 に答える 3

3

私の意見では、より適切な解決策は、ViewModel の SearchString プロパティのセッターからコマンドを呼び出すことです。

于 2012-05-02T11:58:34.357 に答える
2

個人的には、Expression BlendSDKInvokeCommandActionの使用を検討します。

うまくいった例をノックしました。ビューは次のとおりです。

<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>

そして、非常に単純なViewModel(PRISMのDelegateCommandを使用):

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

        public ICommand DoItCommand { get; private set; }
    }

単純な背後にあるコードは、ViewModelを配線します。

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

これを行うためにExpressionBlendを使用する必要もありません。SDKは無料でダウンロードして使用できます。

Expression Blend SDKを使いたくない場合は、MVVMLightが同様のEventToCommandを提供します

もちろん、これを行うことは、ボタンを配置する理由がまだある場合(または、コマンドの実行可能なロジックを利用したい場合)にのみ実際に意味があります。そうでない場合は、プロパティのセッターでロジックを実行できます。

于 2012-05-02T12:05:27.833 に答える
1

コマンドを にバインドすることをお勧めしTextBoxます。多分これは役に立ちます。

于 2012-05-02T11:59:02.727 に答える