如何从DependencyPropertyChanged处理程序更改可视状态
本文关键字:可视 状态 程序 处理 DependencyPropertyChanged | 更新日期: 2023-09-27 18:05:17
第一次从DependencyPropertyChanged处理程序调用时,视觉状态不会改变。
当通过点击按钮或其他事件触发时,同样的视觉状态也会起作用…
<<p> 依赖属性/strong> public bool IsSelected
{
get { return (bool)GetValue(IsSelectedProperty); }
set { this.SetValue(IsSelectedProperty, value); }
}
// Using a DependencyProperty as the backing store for IsSelected. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsSelectedProperty =
DependencyProperty.Register("IsSelected", typeof(bool), typeof(NumericTextBlock), new PropertyMetadata(null, OnIsSelectedChanged));
/// <summary>
/// change event handler, fires when IsSelected property changes
/// </summary>
/// <param name="d"></param>
/// <param name="e"></param>
private static void OnIsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
NumericTextBlock textBlock = d as NumericTextBlock;
if (d != null)
{
bool isSelected = (bool)(e.NewValue ?? false);
if (isSelected)
{
VisualStateManager.GoToState(textBlock, "Selected", true);
}
else
{
if (string.IsNullOrWhiteSpace( textBlock.valueTextBlock.Text))
{
VisualStateManager.GoToState(textBlock, "Normal", true);
}
else
{
VisualStateManager.GoToState(textBlock, "Edit", true);
}
}
}
}
为控件设置IsSelected
<custom:NumericTextBlock IsSelected="True"></custom:NumericTextBlock>
显然,只需要这样做:
protected override void OnApplyTemplate()
{
...
base.OnApplyTemplate();
if (IsSelected)
{
VisualStateManager.GoToState(this, "Selected", true);
}
}