【问题标题】:MVVM - Add a Existing User Control in Grid(XAML)MVVM - 在网格中添加现有用户控件(XAML)
【发布时间】:2014-08-19 09:09:13
【问题描述】:

我正在开发一个Windows 8.1 apps

我正在关注MVVM Pattern

我在应用程序中有一个网格

<Grid Name="g1">

其中需要添加一个现有的用户控件。

<UserControl
    x:Class="CaptureApp.UIComponents.PlayVideo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:CaptureApp.UIComponents"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid>
        <MediaElement Name="MediaPlay" >

        </MediaElement>
    </Grid>
</UserControl>

Since View (XAML) is not allowed to know the Control.

实现它的正确方法是什么??

【问题讨论】:

  • 我不明白你的问题。是什么阻止您在 中声明您的用户控件?
  • 是的,我可以在网格中添加用户控件并处理它在 mvvm 中的可见性,但是当应用程序启动时,用户控件将与主应用程序一起加载。我是否要在单击按钮上创建用户控件的新实例。
  • 试试看rachel53461.wordpress.com/2011/05/28/…。它应该让您了解如何正确使用它。

标签: c# xaml mvvm windows-store-apps


【解决方案1】:

cmets 中的 wordpress 博客使用数据触发器,Windows 商店应用程序中不存在该数据触发器。

如果我正确理解您的问题,您正试图在您的网格中有一个有条件加载的视图,以便当用户控件没有数据时,它不会在网格中呈现?

你可以通过使用

<ContentControl Content="{Binding PropertyOnViewModel}" ContentTemplateSelector="{StaticResource SomeContentTemplateSelector}" />. 

public class SomeContentTemplateSelector : DataTemplateSelector
{
  public DataTemplate SomeTemplate {get;set;}

  protected override DataTemplate SelectTemplate(object item, DependencyObject container)
  {
    if (item is null)
      return null;
    return SomeTemplate;
  }
}

然后在 DataTemplate 中,将您的 UserControl 作为子项。当没有 ContentControl 绑定到 ContentControl 时,这将不显示任何内容,否则将显示提供的 DataTemplate。不过,您需要在包含此 ContentControl 内容的总体 ViewModel 中有一个属性,仅供参考。

编辑:如果您要动态添加多个项目,那么您将需要 ViewModel 上的 ObservableCollection 属性,并使用 ItemsControl 而不是 ContentControl。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    相关资源
    最近更新 更多