最好做什么:
XAML
<TextBlock Text="{Binding}" Name="txtValue" />
代码背后:
public char Value {get;set;}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
txtValue.DataContext = Value;
}
XAML
<TextBlock Text="" Name="txtValue" />
代码背后:
public char Value
{
get {
return (char)GetValue(ValueProperty);
}
set {
SetValue(ValueProperty, value);
}
}
public static DependencyProperty ValueProperty = DependencyProperty.Register(
name: "Value", // Name of property
propertyType: typeof(char), // return type of property
ownerType: typeof(CharacterControl), // who is the owner
typeMetadata: new FrameworkPropertyMetadata(
defaultValue: '0', // default value of property
propertyChangedCallback: ValuePropertyChanged
)
);
// event to fire when property changes
public static void ValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CharacterControl control = d as CharacterControl;
control.Value = (char)e.NewValue;
control.txtValue.Text = control.Value.ToString(); // update value in here <--------------
}
我更喜欢第二个选项,因为我可以在编辑模式下同时看到这个值。我必须为视图编译它以显示正确的值的第一种方法。但我认为第一种选择更有效率? **我会非常快速地更新文本块的值,我不知道使用什么方法。
答案 0 :(得分:3)
在大多数情况下,第一个选项可能更好,因为它更简单。
如果您需要能够在设计模式中看到一个值(我认为您的意思是“编辑模式”),您可以使用XAML中的d:DataContext=
属性设置设计时DataContext。
有关详细信息,请参阅this one等页面。