1

我在程序集中有一个无法更改的控件,它与 .NET 非常相似DateTimePicker。我想在满足某个条件时隐藏该控件的时间选择器部分(我的 ViewModel 上的属性值)。控件如下所示:

[TemplatePart(Name = "PART_DatePicker", Type = typeof (DatePicker))]
[TemplatePart(Name = "PART_TimePicker", Type = typeof (TimePicker))]
public class MyDateTimePicker : Control    {/*...*/}

这个答案显示了一种总是隐藏控件的一部分的好方法,但我想动态地做到这一点:

如何隐藏 WPF 控件的一部分

我想有几种方法可以做到这一点。我想要的是最小的东西(比如链接问题的答案)以及不违反 MVVM 的东西。 System.Interactivity行为和触发器是公平的游戏。

4

3 回答 3

3

创建一个扩展前一个控件的新控件

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 != 没有代码隐藏,没有自定义控件等。

于 2013-01-24T19:48:46.813 回答
0

一种解决方案是在数据模板中定义的 DataTrigger 的帮助下隐藏它,这样当控件的数据上下文中的某个值设置为 true/false 时,您将隐藏/显示该部分。

快速搜索,我发现了一些您可能会觉得有用的链接: http: //zamjad.wordpress.com/2010/06/22/conditionally-hide-controls-from-data-template/ http://social.msdn。 microsoft.com/Forums/en-US/wpf/thread/ae2dbfb7-5dd6-4352-bfa1-53634289329d/

于 2013-01-24T18:44:14.067 回答
0

对我有用的解决方案是编辑控件的样式。使用 Blend,我编辑了 DateTimePicker 样式的副本,并向 TimePicker 的 Visibility 添加了一个绑定,该绑定查看我的 VM 并转换枚举的值。

于 2013-01-24T20:43:37.257 回答