[英]Is send command from ViewModel to View violating MVVM?
我希望将DataGrid
滚动到底部,作为新项添加到基础ObservableCollection
。 为了实现这一点,我制作了一个类似于ICommand
的界面,但是采用了“反向”方式。
public interface IViewModelCommand
{
void Execute(object parameter);
}
履行
public class ViewModelRelayCommand : IViewModelCommand
{
private readonly Action<object> _action;
public ViewModelRelayCommand(Action<object> action)
{
if(action == null)
throw new ArgumentNullException("action");
_action = action;
}
public void Execute(object parameter)
{
_action(parameter);
}
}
我的ViewModel
private IViewModelCommand _scrollAction;
public IViewModelCommand ScrollAction
{
get { return _scrollAction; }
set
{
if (_scrollAction == value)
return;
_scrollAction = value;OnPropertyChanged();
}
}
然后,我为DataGrid创建行为。 (滚动到从此处获取的结束代码)
public sealed class DataGridBehavior : Behavior<DataGrid>
{
public static readonly DependencyProperty ScrollToEndProperty =
DependencyProperty.Register (
"ScrollToEnd",
typeof(IViewModelCommand),
typeof(DataGridBehavior),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None)
);
public IViewModelCommand ScrollToEnd
{
get { return (IViewModelCommand)GetValue(ScrollToEndProperty); }
set { SetValue(ScrollToEndProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
ScrollToEnd = new ViewModelRelayCommand(Scroll);
}
protected override void OnDetaching()
{
base.OnDetaching();
ScrollToEnd = null;
}
private void Scroll(object parameter)
{
var mainDataGrid = AssociatedObject;
if (mainDataGrid.Items.Count > 0)
{
var border = VisualTreeHelper.GetChild(mainDataGrid, 0) as Decorator;
if (border != null)
{
var scroll = border.Child as ScrollViewer;
if (scroll != null) scroll.ScrollToEnd();
}
}
}
}
并将其附加到我的DataGrid
<i:Interaction.Behaviors>
<local:DataGridBehavior ScrollToEnd="{Binding ScrollAction, Mode=OneWayToSource}" />
</i:Interaction.Behaviors>
然后从我的ViewModel中,我只调用if (_scrollAction != null) _scrollAction.Execute(null);
滚动网格,效果很好。
我的问题是,这违反了MVVM吗?
只是一点点...
以我的经验,MVVM是最健康的实践准则。 当您的实际编程任务不需要MVVM时,寻找解决方案来保持MVVM毫无用处,尤其是当您启动并运行有效的解决方案时。
但是您是否想到了事件而不是命令方法?
在这种情况下,这可能对您有用: 当基础Viewmodel指示应该在View触发器上显示WPF EventTrigger时,该如何?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.