我有一個網格顯示人員的observableCollection的內容,兩個文本框顯示所選行的屬性。如果您願意的話,可以使用主從式視圖。用IsSynchronizedWithCurrentItem綁定到viewmodel中的集合
當分配的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中,而是位於視圖模型(它被分配給窗口的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));
}
我想不會重新分配在一個較低的水平一個DataContext在視覺樹,或與電網的selectedItem屬性綁定。
這樣可以使用這種機制嗎?
謝謝!
我會推薦不同的實現視圖模型。要麼實現你自己的ViewModelBase,它實現'INotifyPropertyChanged'或(更好的IMO)使用MVVM框架,例如[MVVMLight](http://mvvmlight.codeplex.com/),它給你一個體面的ViewModelBase是免費的。您通常不必在ViewModel中使用依賴項屬性。 – EagleBeak