0

Persons の observableCollection の内容を表示するグリッドと、選択した行のプロパティを表示する 2 つのテキスト ボックスがあります。必要に応じて、マスター詳細ビュー。

observablecollection を datacontext に割り当てるときは、次のように簡単に実行できます。

<Grid>
    <Grid Background="Gray">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition Height="30"></RowDefinition>
        </Grid.RowDefinitions>
        <igWPF:XamDataGrid Grid.Row="0" DataSource="{Binding}" IsSynchronizedWithCurrentItem="True" />

        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <TextBox Height="21" Width="100" Margin="5,0,5,0" Text="{Binding Name}"></TextBox>
            <TextBox Height="21" Width="100" Text="{Binding Age}"></TextBox>
        </StackPanel>
    </Grid>

 </Grid>

IsSynchronizedWithCurrentItem プロパティは、グリッドで選択された項目がテキスト ボックスで処理される項目であることを確認します。

observablecollection が datacontext に直接ではなく、viewmodel (ウィンドウの datacontext に割り当てられている) にある場合に、これとまったく同じことを実行できるかどうか疑問に思っていました。

public class TestViewModel: DependencyObject
{
    public TestViewModel(){
        Results = new ObservableCollection<Person>();

        Results.Add(new Person { Age = "23", Name = "Able" });
        Results.Add(new Person { Age = "25", Name = "Baker" });
    }

    public ObservableCollection<TagDlgmtEntity> Results
    {
        get { return (ObservableCollection<Person>)GetValue(ResultsProperty); }
        set { SetValue(ResultsProperty, value); }
    }

    public static readonly DependencyProperty ResultsProperty =
        DependencyProperty.Register("Results", typeof(ObservableCollection<Person>), typeof(TestViewModel), new PropertyMetadata(null));
}

ビジュアル ツリーの下位レベルでデータ コンテキストを再割り当てしたり、グリッドの selectedItem プロパティにバインドしたりしたくありません。

このメカニズムをこのように使用することは可能ですか?

ありがとう!

4

1 に答える 1

0

はい、可能です。次のようにバインディングを宣言します。 DataSource="{Binding Results}"


ViewModel の例

仮定:ViewModelBase実装INotifyPropertyChanged(質問に対する私のコメントを参照)

public class MainWindowViewModel : ViewModelBase
{
    private readonly List<Person> _results;

    public MainWindowViewModel()
    {
        _results = new List<Person>
        {
            new Person {Age = "23", Name = "Able"},
            new Person {Age = "25", Name = "Baker"}
        };

        ResultsView = CollectionViewSource.GetDefaultView(_results);

        ResultsView.CurrentChanged += (sender, args) => RaisePropertyChanged(() => Name);
    }

    public ICollectionView ResultsView { get; private set; }

    public string Name
    {
        get
        {
            return ((Person) ResultsView.CurrentItem).Name;
        }
    }
}
于 2013-10-01T07:28:48.663 に答える