主办ContentControl中的ViewModels在WPF [英] Hosting ViewModels in ContentControl in WPF

查看:98
本文介绍了主办ContentControl中的ViewModels在WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在底部的顶部状态栏菜单栏传统的形式布局。当用户选择一个菜单项之间在(窗体的全部剩余客户区)的空间被替换为用户控件 - 想到一个SDI应用程序,可以承载多种类型的文件

I have a traditional form layout with a menu bar at the top and status bar at the bottom. When the user selects a menu item, the space in-between (the form's entire remaining client area) gets replaced with a user control - think of an SDI app that can host multiple types of documents.

如果你知道一个更好的方式去了解这一点,请附和,对于现在,我试图让它在一个非常简化的版本与ContentControl中工作,但我不能让它更新当其DataContext设置屏幕。

If you know of a better way to go about this, please chime in. For now, I'm trying to get it to work in a very simplified version with a ContentControl, but I cannot get it to update the screen when its DataContext is set.

下面是ViewModelA非常简单的代码。 。ViewModelB是相同的,除了烧烤

Here's the very simple code for ViewModelA. ViewModelB is identical, except for the Bs.

namespace Dynamic_ContentControl
{
    public class ViewModelA: ViewModelBase
    {
        public ViewModelA()
        {
            DisplayName = "This is A";
        }
    }
}

主窗口是非常简单的。它基本上声明一个属性来保存所承载的控件的视图模型,并公开了两个命令来指定视图模型A或B。

The main window is very simple. It basically declares a property to hold the view model of the hosted control and exposes two commands to assign view models A or B.

namespace Dynamic_ContentControl
{
    public class MainViewModel: ViewModelBase
    {
        private ViewModelBase clientContent = null;

        public ICommand ShowA { get; private set; }
        public ICommand ShowB { get; private set; }
        public ViewModelBase ClientContent {
            get
            {
                return clientContent;
            }
            private set
            {
                clientContent = value;
                OnPropertyChanged("ClientContent");
            }
        }
        public MainViewModel()
        {
            ShowA = new RelayCommand((obj) =>
            {
                ClientContent = new ViewModelA();
            });
            ShowB = new RelayCommand((obj) =>
            {
                ClientContent = new ViewModelB();
            });
        }
    }
}



最后,XAML声明了一个ContentControl中并设置其的ContentTemplate一个叫ClientAreaTemplate,其ContentPresenter点到另一个的DataTemplate的DataTemplate,名为TextBlockLayout:

Finally, the XAML declares a ContentControl and sets its ContentTemplate to a DataTemplate called ClientAreaTemplate, whose ContentPresenter points to another DataTemplate, named TextBlockLayout:

<Window x:Class="Dynamic_ContentControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:Dynamic_ContentControl"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <vm:MainViewModel />
    </Window.DataContext>
    <Window.Resources>
        <DataTemplate x:Key="TextBlockLayout">
            <TextBlock Text="{Binding Path=DisplayName}" />
        </DataTemplate>
        <DataTemplate x:Key="ButtonLayout">
            <Button Content="{Binding Path=DisplayName}" />
        </DataTemplate>
        <DataTemplate x:Key="CheckBoxLayout">
            <CheckBox Content="{Binding Path=DisplayName}" />
        </DataTemplate>
        <DataTemplate x:Key="ClientAreaTemplate">
            <ContentPresenter x:Name="ContentArea" ContentTemplate="{StaticResource ResourceKey=TextBlockLayout}"/>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding Path=DataContext}"
                             Value="{x:Type vm:ViewModelB}">
                    <Setter TargetName="ContentArea"
                            Property="ContentTemplate"
                            Value="{StaticResource ResourceKey=ButtonLayout}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=DataContext}"
                             Value="{x:Type vm:ViewModelB}">
                    <Setter TargetName="ContentArea"
                            Property="ContentTemplate"
                            Value="{StaticResource ResourceKey=CheckBoxLayout}" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Button Content="Show A"
                Command="{Binding Path=ShowA}"
                HorizontalAlignment="Left"
                Margin="10,10,0,0"
                VerticalAlignment="Top"
                Width="75" />
        <Button Content="Show B"
                Command="{Binding ShowB}"
                HorizontalAlignment="Left"
                Margin="90,10,0,0"
                VerticalAlignment="Top"
                Width="75" />
        <Label Content="{Binding Path=ClientContent.DisplayName}"
               HorizontalAlignment="Left"
               Margin="170,8,0,0"
               VerticalAlignment="Top" />
        <ContentControl DataContext="{Binding Path=ClientContent}"
                        Content="{Binding}"
                        ContentTemplate="{StaticResource ResourceKey=ClientAreaTemplate}"
                        HorizontalAlignment="Left"
                        Margin="10,37,0,0"
                        VerticalAlignment="Top"
                        Height="198"
                        Width="211" />

    </Grid>
</Window>



预期的行为

Expected behaviour

当屏幕打开时,我想TextBoxLayout显示。如果用户然后对两个按钮中的一个点击,它应该加载任一个ButtonLayout或CheckBoxLayout,根据实际运行时类型分配视图模型的

When the screen opens, I want TextBoxLayout to display. If the user then clicks on one of the two buttons, it should load either a ButtonLayout or CheckBoxLayout, depending on the actual runtime type of the view model that is assigned.

实际行为

Actual behaviour

屏幕与TextBoxLayout加载打开,但它永远不会改变,以另一种类型,我点击的按钮。

The screen opens with the TextBoxLayout loaded, but it never changes to another type as I click the buttons.

我认为这个问题是DataTrigger尝试与类型进行比较的方式,但也有在所有的输出窗口中没有约束力的消息

I think the problem is the way the DataTrigger tries to compare with the type, but there are no binding messages at all the Output window.

推荐答案

在这种情况下,你需要使用的 DataTemplateSelector

In this situation, you need to use DataTemplateSelector:

提供一种方法来选择一个基于数据对象和数据绑定在的DataTemplate 元素。

Provides a way to choose a DataTemplate based on the data object and the data-bound element.

在这里 是动态的版本 DataTemplateSelector 返回所需的的DataTemplate 根据不同的类型:

Here is a version of dynamic DataTemplateSelector which returns a desired DataTemplate depending on the type:

/// <summary>
/// Provides a means to specify DataTemplates to be selected from within WPF code
/// </summary>
public class DynamicTemplateSelector : DataTemplateSelector
{
    /// <summary>
    /// Generic attached property specifying <see cref="Template"/>s
    /// used by the <see cref="DynamicTemplateSelector"/>
    /// </summary>
    /// <remarks>
    /// This attached property will allow you to set the templates you wish to be available whenever
    /// a control's TemplateSelector is set to an instance of <see cref="DynamicTemplateSelector"/>
    /// </remarks>
    public static readonly DependencyProperty TemplatesProperty =
        DependencyProperty.RegisterAttached("Templates", typeof(TemplateCollection), typeof(DataTemplateSelector),
        new FrameworkPropertyMetadata(new TemplateCollection(), FrameworkPropertyMetadataOptions.Inherits));


    /// <summary>
    /// Gets the value of the <paramref name="element"/>'s attached <see cref="TemplatesProperty"/>
    /// </summary>
    /// <param name="element">The <see cref="UIElement"/> who's attached template's property you wish to retrieve</param>
    /// <returns>The templates used by the givem <paramref name="element"/>
    /// when using the <see cref="DynamicTemplateSelector"/></returns>
    public static TemplateCollection GetTemplates(UIElement element)
    {
        return (TemplateCollection)element.GetValue(TemplatesProperty);
    }

    /// <summary>
    /// Sets the value of the <paramref name="element"/>'s attached <see cref="TemplatesProperty"/>
    /// </summary>
    /// <param name="element">The element to set the property on</param>
    /// <param name="collection">The collection of <see cref="Template"/>s to apply to this element</param>
    public static void SetTemplates(UIElement element, TemplateCollection collection)
    {
        element.SetValue(TemplatesProperty, collection);
    }

    /// <summary>
    /// Overriden base method to allow the selection of the correct DataTemplate
    /// </summary>
    /// <param name="item">The item for which the template should be retrieved</param>
    /// <param name="container">The object containing the current item</param>
    /// <returns>The <see cref="DataTemplate"/> to use when rendering the <paramref name="item"/></returns>
    public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
    {
        //This should ensure that the item we are getting is in fact capable of holding our property
        //before we attempt to retrieve it.
        if (!(container is UIElement))
            return base.SelectTemplate(item, container);

        //First, we gather all the templates associated with the current control through our dependency property
        TemplateCollection templates = GetTemplates(container as UIElement);
        if (templates == null || templates.Count == 0)
            base.SelectTemplate(item, container);

        //Then we go through them checking if any of them match our criteria
        foreach (var template in templates)
            //In this case, we are checking whether the type of the item
            //is the same as the type supported by our DataTemplate
            if (template.Value.IsInstanceOfType(item))
                //And if it is, then we return that DataTemplate
                return template.DataTemplate;

        //If all else fails, then we go back to using the default DataTemplate
        return base.SelectTemplate(item, container);
    }
}

/// <summary>
/// Holds a collection of <see cref="Template"/> items
/// for application as a control's DataTemplate.
/// </summary>
public class TemplateCollection : List<Template>
{

}

/// <summary>
/// Provides a link between a value and a <see cref="DataTemplate"/>
/// for the <see cref="DynamicTemplateSelector"/>
/// </summary>
/// <remarks>
/// In this case, our value is a <see cref="System.Type"/> which we are attempting to match
/// to a <see cref="DataTemplate"/>
/// </remarks>
public class Template : DependencyObject
{
    /// <summary>
    /// Provides the value used to match this <see cref="DataTemplate"/> to an item
    /// </summary>
    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(Type), typeof(Template));

    /// <summary>
    /// Provides the <see cref="DataTemplate"/> used to render items matching the <see cref="Value"/>
    /// </summary>
    public static readonly DependencyProperty DataTemplateProperty =
       DependencyProperty.Register("DataTemplate", typeof(DataTemplate), typeof(Template));

    /// <summary>
    /// Gets or Sets the value used to match this <see cref="DataTemplate"/> to an item
    /// </summary>
    public Type Value
    { get { return (Type)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } }

    /// <summary>
    /// Gets or Sets the <see cref="DataTemplate"/> used to render items matching the <see cref="Value"/>
    /// </summary>
    public DataTemplate DataTemplate
    { get { return (DataTemplate)GetValue(DataTemplateProperty); } set { SetValue(DataTemplateProperty, value); } }
}



示例

<local:DynamicTemplateSelector x:Key="MyTemplateSelector" />

<DataTemplate x:Key="StringTemplate">
    <TextBlock>
        <Run Text="String: " />
        <Run Text="{Binding}" />
    </TextBlock>
</DataTemplate>

<DataTemplate x:Key="Int32Template">
    <TextBlock>
        <Run Text="Int32: " />
        <Run Text="{Binding}" />
    </TextBlock>
</DataTemplate>

<Style x:Key="MyListStyle" TargetType="ListView">
    <Setter Property="ItemTemplateSelector" Value="{StaticResource MyTemplateSelector}"/>
    <Setter Property="local:DynamicTemplateSelector.Templates">
        <Setter.Value>
            <local:Templates>
                <local:Template Value={x:Type String} DataTemplate={StaticResource StringTemplate}/>
                <local:Template Value={x:Type Int32} DataTemplate={StaticResource Int32Template}/>
            </local:Templates>
        </Setter.Value>
    </Setter>
</Style>

这篇关于主办ContentControl中的ViewModels在WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆