【问题标题】:How to do data binding in an ItemsControl (MVVM)如何在 ItemsControl (MVVM) 中进行数据绑定
【发布时间】:2014-09-03 20:30:28
【问题描述】:

我知道这很简单,但我做不到。这将有助于理解 ItemsControl 中的 DataBinding。

我在 ScrollViewer 中有一个 ItemsControl。 ItemsControl 将用于更改存储在 OvservableCollection 设置中的子视图。

Settings 和 CurrentViewModel 都在主窗口的 ViewModel 中。在主视图模型中,我想通过更改 CurrentViewModel 来更改显示的内容。

如果我将 ObservableCollection、设置作为 ItemsControl 源,那么它可以遍历集合的每个项目——这不是我需要的。那么这是如何正确完成的呢?

我知道我会得到答案,但请告知。经过几个小时的谷歌,我无法解决这个问题。 (我希望我的问题很清楚)。提前致谢。

 private SettingsViewModelBase currentViewModel;
    public SettingsViewModelBase CurrentViewModel
    {
        get
        {
            return currentViewModel;
        }
        set
        {
            if (currentViewModel == value)
                return;
            currentViewModel = value;
            OnPropertyChanged("CurrentViewModel");
        }
    }

private readonly ObservableCollection<SettingsViewModelBase> settings;

    public ObservableCollection<SettingsViewModelBase> Settings
    {
        get { return this.settings; }
    } 


<ScrollViewer Grid.Row="2" Name="scrollviewer1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" >

        <ItemsControl 
                ItemsSource="{Binding ????}"
                >

             <ItemsControl.Resources>
                <DataTemplate DataType="{x:Type vm_1}">  <vm_1_View/>
                </DataTemplate>
                <DataTemplate DataType="{x:Type vm_2}">  <vm_2_view/>
                </DataTemplate>
            </ItemsControl.Resources>

            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ContentControl  Content="{Binding ?????" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

    </ScrollViewer>

【问题讨论】:

  • 你试过{Binding Settings}吗?因为非常明显?
  • @会的。没用。

标签: wpf mvvm data-binding itemscontrol


【解决方案1】:

如果您只想一次显示一个视图,那么您可以在主视图中使用单个ContentControl 将数据绑定到主视图模型中的CurrentViewModel 属性:

<ContentControl Content="{Binding CurrentViewModel" />

然后在主视图模型中,大概是为了响应一些 UI 动作,你可以只更改 CurrentViewModel 属性的值:

CurrentViewModel = new vm_2();

您可以将您的DataTemplates 放入App.xaml Resources 部分,然后它们将在应用程序范围内可用。

【讨论】:

  • “单一”是指根本不使用 ItemsControl?
  • 就是这样——根本不要使用 ItemsControl。
  • 是的,你明白了。现在您可以将不同的ICommands 连接到一些ButtonMenuItem Command 属性,每个属性都将CurrentViewModel 设置为不同的视图模型,并且您拥有自己的应用程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 2011-06-13
  • 2010-12-20
  • 1970-01-01
相关资源
最近更新 更多