【发布时间】:2014-06-04 10:01:59
【问题描述】:
让我们看两个例子:
设置焦点
为了获得焦点,我们必须在代码隐藏中调用 方法 UIelement.Focus(),因此 MVVM 中的标准方法是创建 *behaviour`:
public static class FocusedBehavior
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty =
DependencyProperty.RegisterAttached("IsFocused", typeof(bool), typeof(FocusedBehavior), new UIPropertyMetadata(false, OnIsFocusedChanged));
private static void OnIsFocusedChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if((bool)e.NewValue)
(sender as UIElement).Focus();
}
}
然后对于 每个 控件,我们希望能够设置焦点
<Button ... local:FocusedBehavior.IsFocused="{Binding SomeDependencyProperty}"/>
必须在 ViewModel 中为 每个 控件单独创建 bool SomeDependencyProperty。这样 ViewModel 可以通过设置其自身属性的值来更改 View 中的某些内容。
控制模糊
要设置模糊(see here),我们必须更改属性BlurEffect.Radius。这可以很简单
<Window.Effect>
<BlurEffect Radius="{Binding SomeDependencyProperty}"/>
</Window.Effect>
int SomeProperty 所在的位置必须在 ViewModel 中针对每种情况亲自创建。
问题
还有其他方法可以在 View by ViewModel 中进行更改吗?
我想知道能够使用最合适的所有可能性。要设置焦点,我们必须使用 behaviour 方法来设置模糊简单绑定。还有更多可能吗?
非常通用的解决方案是让 ViewModel 知道 View,这样它就可以在处理命令时调用方法和使用属性,但这是个坏主意。正确的?虽然在这种情况下 View 可以扩展自身,使用公共属性和方法来实现某些结果(例如,设置焦点或设置模糊)。
【问题讨论】: