我想写一个条件控制如下:
<local:ConditionalBlock Condition={Binding CertainBoolValue}>
<ConditionalBlock.Match>
<!-- Any content here -->
</ConditionalBlock.Match>
<ConditionalBlock.Else>
<!-- Any content here -->
</ConditionalBlock.Else>
</local:ConditionalBlock>
目前我不知道这应该如何实施。所以请帮忙。谢谢
编辑
在等待响应时,我使用自定义控件和控件模板实现了自己的解决方案,如下所示:
using System.Windows;
using System.Windows.Controls;
namespace Sample
{
public class ConditionalControl : ContentControl
{
static ConditionalControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ConditionalControl), new FrameworkPropertyMetadata(typeof(ConditionalControl)));
}
public object Alternative
{
get { return (object)GetValue(AlternativeProperty); }
set { SetValue(AlternativeProperty, value); }
}
public static readonly DependencyProperty AlternativeProperty =
DependencyProperty.Register("Alternative", typeof(object), typeof(ConditionalControl), new UIPropertyMetadata(null));
public bool Condition {
get { return (bool)GetValue(ConditionProperty); }
set { SetValue(ConditionProperty, value); }
}
public static readonly DependencyProperty ConditionProperty =
DependencyProperty.Register("Condition", typeof(bool), typeof(ConditionalControl), new UIPropertyMetadata(null));
}
}
条件控制.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Sample">
<Style TargetType="{x:Type local:ConditionalControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ConditionalControl}">
<Grid>
<ContentPresenter Name="match"/>
<ContentPresenter Name="alternative" ContentSource="Alternative" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="Condition" Value="True">
<Setter TargetName="match" Property="Visibility" Value="Visible"/>
<Setter TargetName="alternative" Property="Visibility" Value="Collapsed"/>
</Trigger>
<Trigger Property="Condition" Value="False">
<Setter TargetName="match" Property="Visibility" Value="Collapsed"/>
<Setter TargetName="alternative" Property="Visibility" Value="Visible"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
示例用法:
<Grid>
<local:ConditionalControl Condition="{Binding CertainBoolValue}">
<Label>Match case</Label>
<local:ConditionalControl.Alternative>
<Label>Alternative case</Label>
</local:ConditionalControl.Alternative>
</local:ConditionalControl>
</Grid>
无论如何,感谢卢克伍德沃德的及时回复。我会将您的答案标记为已接受