0
我想下面寫一個條件控制:條件塊在XAML
<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));
}
}
ConditionalControl.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>
無論如何,感謝Luke Woodward的及時迴應。我還是選你的答案接受
你看過DataTriggers嗎?您可以將DataTrigger放入基於條件 – cordialgerm
使用不同ControlTemplates的樣式中。使用此處所述的轉換器可以獲得/類似/功能:http://blog.greatrexpectations.com/2012/10/04/getting-rid -of-xaml-boilerplate/ –
@pickles:謝謝,我在我的解決方案中使用了ControlTemplate.Triggers – CEDA