我正在尝试在 silverlight 中创建一个登录状态控件,我将在其中使用多个 ControlTemplate 来定义条件内容。
到目前为止,我已经创建了一个 LoginStatusControl
public class LoginStatusControl : ContentControl
{
// these are actually Depedency Properties
public ControlTemplate LoggedInTemplate { get; set; }
public ControlTemplate AnonymousTemplate { get; set; }
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var user = this.DataContext as User;
if (user == null && this.AnonymousTemplate != null)
{
this.Template = this.AnonymousTemplate;
}
else if (this.LoggedInTemplate != null)
{
this.Template = this.LoggedInTemplate;
}
}
}
然后我在 Style 中定义了模板。
<Style x:Key="UserStatusStyle" TargetType="local:LoginStatusControl">
<Setter Property="LoggedInTemplate">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="User " />
<TextBlock Text="{Binding FirstName}" />
<TextBlock Text=" " />
<TextBlock Text="{Binding LastName}" />
<TextBlock Text=" is logged in" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="AnonymousTemplate">
<Setter.Value>
<ControlTemplate>
<TextBlock Text="Please create your profile" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我在连接条件模板以覆盖 ControlTemplate 时遇到困难。
在搜索时,我发现了这个问题并尝试使用模板绑定,但我无法让它工作。
无论如何,如果用户登录或未登录,是否可以显示此条件模板?还有另一种方法可以解决我缺少的这个问题吗?我希望提出一个解决方案,可以在控件的 DataContext 更改时动态更新模板。