簡體   English   中英

MVVM-在網格(XAML)中添加現有的用戶控件

[英]MVVM - Add a Existing User Control in Grid(XAML)

我正在開發Windows 8.1 apps

我正在遵循MVVM模式

我在應用程序中有一個網格

<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.

什么是實現它的正確方法?

評論中的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綁定的內容時,這將不顯示任何內容,否則將顯示提供的DataTemplate。 您將需要在總體ViewModel中具有一個屬性,該屬性包含此ContentControl的內容,盡管如此。

編輯:如果要動態添加多個項目,則將需要ViewModel上的ObservableCollection <>屬性,並使用ItemsControl而不是ContentControl。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM