如何从 Dependency PropertyChanged 处理程序更改视觉状态?
How to change visual state from DependencyPropertyChanged handler?
第一次从 DependencyPropertyChanged 处理程序调用时,视觉状态没有改变。
通过单击按钮或其他事件触发时,相同的视觉状态会起作用...
依赖关系属性
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);
}
}
}
}
为控件选择设置
<custom:NumericTextBlock IsSelected="True"></custom:NumericTextBlock>
显然,只需要这样做:
protected override void OnApplyTemplate()
{
...
base.OnApplyTemplate();
if (IsSelected)
{
VisualStateManager.GoToState(this, "Selected", true);
}
}
第一次从 DependencyPropertyChanged 处理程序调用时,视觉状态没有改变。
通过单击按钮或其他事件触发时,相同的视觉状态会起作用...
依赖关系属性
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);
}
}
}
}
为控件选择设置
<custom:NumericTextBlock IsSelected="True"></custom:NumericTextBlock>
显然,只需要这样做:
protected override void OnApplyTemplate()
{
...
base.OnApplyTemplate();
if (IsSelected)
{
VisualStateManager.GoToState(this, "Selected", true);
}
}