【问题标题】:Binding to collection in viewmodel with IsSynchronizedWithCurrentItem使用 IsSynchronizedWithCurrentItem 绑定到视图模型中的集合
【发布时间】:2013-10-01 07:13:42
【问题描述】:

我有一个显示 observableCollection Persons 内容的网格,以及两个显示所选行属性的文本框。如果你愿意的话,一个主细节视图。

将 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 不是直接在数据上下文中,而是位于视图模型(分配给窗口的数据上下文)中时,是否可以执行此操作。

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 属性绑定。

这种方式可以使用这种机制吗?

谢谢!

【问题讨论】:

  • 我建议以不同的方式实现 ViewModel。要么实现你自己的 ViewModelBase,它实现了INotifyPropertyChanged,要么(更好的 IMO)使用 MVVM 框架,例如MVVMLight,它免费为您提供了一个不错的 ViewModelBase。您通常不必在 ViewModel 中摆弄依赖属性。

标签: wpf grid master-detail selecteditem


【解决方案1】:

是的,这是可能的。像这样声明你的绑定: DataSource="{Binding Results}"


示例视图模型

假设: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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2012-07-19
    • 2012-01-16
    相关资源
    最近更新 更多