2012-07-05 147 views
1

我想根據屬性有條件地加載用戶控件。如果該屬性爲「true」,那麼我們將用戶控件加載到XAML中。假設該酒店被命名爲:IsCameraSupported。將Visibility設置爲Collapsed如果不是是正確的解決方案,因爲我完全不希望將其包含在XAML文件中。有條件地加載用戶控件

有人可以給我一個代碼示例來做到這一點,只在XAML?

非常感謝。

回答

-1

使用觸發器或設置能見度倒塌時年布爾運行時也是如此

一個轉換器類喲能做到這一點

if(IsCameraSupported) 
{ 
    var myControl = new MyControl(); 
    MyCanvas.Children.Add(myControl); 
    Canvas.SetLeft(myControl, 20); 
    Canvas.SetTop(myControl, 20); 

} 
+0

看來你還沒有明白我的意思。如果屬性爲false,我不想包含UserControl。將可見性設置爲摺疊狀態仍將加載UserControl,但不可見並且不佔用空間。 –

+0

而且你絕對不想在運行時使用代碼/設置代碼 – JohnnBlade

0

編輯 我誤解了這個問題乍看。這是更新後的回覆。

您可以使用框架控件。在框架控件中,您可以導航到具有相機控件的頁面。

如何從視圖模型

  1. 火從視圖模型IsCameraSupported二傳手事件調用視圖的方法。
  2. 訂閱查看模型事件
  3. 調用Frame.Navigate在視圖代碼後面的事件處理程序中。

原來的答案

您可以創建BooleanToVisibilityConverter,並使用數據綁定。

http://www.rhyous.com/2011/02/22/binding-visibility-to-a-bool-value-in-wpf/

http://msdn.microsoft.com/en-us/library/system.windows.controls.booleantovisibilityconverter.aspx

轉換代碼

public class BooleanVisibilityConverter : IValueConverter 
{ 
    #region Constructors 

    public BooleanVisibilityConverter() 
     : this(true) 
    { } 

    public BooleanVisibilityConverter(bool collapseWhenInvisible) 
     : base() 
    { 
     CollapseWhenInvisible = collapseWhenInvisible; 
    } 

    #endregion 

    #region Properties 

    public bool CollapseWhenInvisible { get; set; } 

    public Visibility FalseVisibility 
    { 
     get 
     { 
      if (CollapseWhenInvisible) 
       return Visibility.Collapsed; 
      else 
       return Visibility.Hidden; 
     } 
    } 

    #endregion 

    #region IValueConverter Members 

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value == null) 
      return Visibility.Visible; 
     if ((bool)value) 
      return Visibility.Visible; 
     else 
      return FalseVisibility; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     if (value == null) 
      return true; 
     return ((Visibility)value == Visibility.Visible); 
    } 

    #endregion 
} 
+0

設置可見性不是解決方案,因爲它仍將加載UserControl並執行一些初始化過程。 –

-1

我會用一個ContentControl,並在DataTriggerContentTemplate設爲您的UserControl如果IsCameraSupportedTrue

<DataTemplate x:Key="MyUserControlTemplate"> 
    <local:MyUserControl /> 
</DataTemplate> 

<ContentControl> 
    <ContentControl.Style> 
     <Style TargetType="{x:Type ContentControl}"> 
      <Style.Triggers> 
       <DataTrigger Property="{Binding IsCameraSupported}" Value="True"> 
        <Setter Property="ContentTemplate" Value="{StaticResource MyUserControlTemplate}" /> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </ContentControl.Style> 
</ContentControl>