C# 有条件地加载用户控件
我想根据属性有条件地加载UserControl。如果属性为“true”,那么我们将在XAML中加载UserControl。假设属性名为:C# 有条件地加载用户控件,c#,wpf,C#,Wpf,我想根据属性有条件地加载UserControl。如果属性为“true”,那么我们将在XAML中加载UserControl。假设属性名为:IsCameraSupported。将可见性设置为折叠应该是正确的解决方案,因为我完全不想将其包含在XAML文件中 有人能给我一个代码示例来做这件事吗,仅在XAML中 非常感谢。使用触发器或转换器类,在yr bool为真时将可见性设置为“折叠” 在运行时,您可以这样做 if(IsCameraSupported) { var myControl = new
IsCameraSupported
。将可见性
设置为折叠
应该是正确的解决方案,因为我完全不想将其包含在XAML文件中
有人能给我一个代码示例来做这件事吗,仅在XAML中
非常感谢。使用触发器或转换器类,在yr bool为真时将可见性设置为“折叠” 在运行时,您可以这样做
if(IsCameraSupported)
{
var myControl = new MyControl();
MyCanvas.Children.Add(myControl);
Canvas.SetLeft(myControl, 20);
Canvas.SetTop(myControl, 20);
}
编辑
我一眼就误解了这个问题。这是最新的答复
可以使用帧控制。在帧控件中,可以导航到具有摄影机控件的页面
如何从视图模型调用视图方法
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
}
我会使用
ContentControl
并在DataTrigger
中设置ContentTemplate
到UserControl
如果iscamerasupport
为True
<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>
看来你还没有明白我的意思。如果属性为false,我不想包含UserControl。将可见性设置为collapsed将仍然加载UserControl,但不可见且不占用空间。并且您绝对不希望使用代码隐藏/在运行时设置可见性。可见性不是解决方案,因为它仍将加载UserControl并执行一些初始化过程。