创建一个扩展前一个控件的新控件
public sealed class MySuperiorDateTimePicker : MyDateTimePicker
{
//....
添加一个可以绑定到 ViewModel 状态的 DependencyProperty
public static readonly DependencyProperty HideItProperty =
DependencyProperty.Register(
"HideIt",
typeof(bool),
typeof(MySuperiorDateTimePicker ),
new UIPropertyMetadata(false, HideItPropertyChanged));
//snip property impl
等待属性改变,然后隐藏你的 UI
private static void HideItPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
(d as MySuperiorDateTimePicker).OnHideItChanged((bool)e.OldValue,
(bool)e.NewValue);
}
private void OnHideItChanged(bool oldValue, bool newValue)
{
if(BusyTemplate == null)
return;
FindTimePicker().Visibility = newValue ? Visibility.Visible :
Visibility.Collapsed;
}
private UIElement FindTimePicker()
{
//snip null checks
return GetTemplateChild("PART_TimePicker") as UIElement;
}
请小心,FindTimePicker
因为您的 DP 可能会在加载控件之前更改,并且GetTemplateChild
将返回 null。通常要做的事情是OnHideItChanged
,如果GetTemplateChild
返回null用于稍后(或更早)Dispatcher.BeginInvoke
重新运行事件处理程序。ApplicationIdle
当你发现自己在说“我如何使用 MVVM 完成 UI 工作”时,停下来重新思考你的真正目标。MVVM != 没有代码隐藏,没有自定义控件等。