概述
本文描述WPF的附加属性。对于使用MVVM框架的项目,附加属性是非常重要的一个特性。
在MVVM框架下,ViewModel的代码通过控件的依赖属性来控制控件的,例如:
//ViewModel public Visibility GridVisibility {get;set} public void Show() { GridVisibility = Visibility.Visible; } public void Hide() { GridVisibility = Visibility.Collapsed; } //View <Grid Visibility="{Binding GridVisibility}"> </Grid>
可以看出,我们通过修改GridVisibility 的值就改变了Grid的状态。
现在有一个需求,要求在执行某个命令时,将输入焦点定位到一个TextBox,我想TextBox是否有一个属性:IsFocused?有就简单了!事实上TextBox并没有这个依赖属性,这就麻烦了。如果不采用MVVM,我在代码中执行txtBoxName.Focus();也就搞定了,但MVVM模式下没有这种操作。这时候附加属性就派上用场了。
你没有IsFocused这个属性,我给你加一个:
public class TextBoxHelper { /// <summary> /// 附加属性:IsFocused /// </summary> public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(TextBoxHelper), new FrameworkPropertyMetadata(false, OnIsFocusedPropertyChanged)); public static void SetIsFocused(DependencyObject dp, bool value) { dp.SetValue(IsFocusedProperty, value); } public static bool GetIsFocused(DependencyObject dp) { return (bool)dp.GetValue(IsFocusedProperty); } private static void OnIsFocusedPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { TextBox textBox = sender as TextBox; if ((bool)e.NewValue) { textBox.Focus(); textBox.SelectAll(); } } }
以上就是这个附加属性的定义。下面需要把这个属性提供给控件:
<UserControl x:Class="LearnWPF.Pages.PageBasicCharacteristicView" xmlns:xy="clr-namespace:LearnWPF.Controls.Helper;assembly=LearnWPF.Controls"> <TabControl> <TabItem Header="附加属性"> <Grid> <TextBox xy:TextBoxHelper.IsFocused="{Binding IsTextBox2Focused}"/> <Button Content="Focus TextBox2" Command="{s:Action FocusTextBox2}"/> </Grid> </TabItem> </TabControl> </UserControl>
然后,ViewModel中操作 IsTextBox2Focused即可控制TextBox的焦点了。
public class PageBasicCharacteristicViewModel : Screen { public bool IsTextBox2Focused { get; set; } public void FocusTextBox2() { IsTextBox2Focused = true; } }
资源
系列目录:WPF开发快速入门【0】前言与目录
代码下载:Learn WPF: WPF学习笔记 (gitee.com)
标签:入门,void,附加,bool,WPF,TextBox,public,属性 From: https://www.cnblogs.com/seabluescn/p/16579276.html