【发布时间】:2012-02-03 10:52:51
【问题描述】:
视图模型:
public class MyViewModel : INotifyPropertyChanged
{
public string MyText { ... }
}
XAML:
<my:MySpecialTextBox Text="{Binding MyText}" />
自定义控件:
public class MySpecialTextBox : TextBox
{
static MySpecialTextBox()
{
TextProperty.OverrideMetadata(typeof(MySpecialTextBox),
new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
DefaultValue = string.empty,
PropertyChangedCallback = OnTextPropertyChanged
});
}
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as MySpecialTextBox;
if (control != null)
{
control.Text = SomeAdjustedValue((string)e.NewValue);
}
}
}
问题在于,虽然自定义控件中的 DependencyProperty 可以正确调整,但它不会更新 ViewModel。我意识到由于 SomeAdjustedValue 的命名,这个似乎应该是 CoerceValueCallback,但 Coercion 也不会更改 ViewModel 值。如果它是 OnTextPropertyChanged 回调的触发器,我似乎无法更新我的 ViewModel 中的值......我做了一个调试跟踪,它没有第二次使用新值通过 ViewModel。不知道该怎么做才能解决这个问题。
【问题讨论】:
-
只是为了确保我理解-您期望 ViewModel 发生更改,通过 PropertyChanged 通知提升到 UI,以更新 UI,然后由于绑定回调,随后被路由回到 ViewModel?
标签: c# wpf data-binding mvvm dependency-properties