簡體   English   中英

將RoutedEvent或RoutedCommand冒泡到ViewModel

[英]Bubbling RoutedEvent or RoutedCommand to a ViewModel

我有一個ViewModel集合,它們使用樣式呈現為制表符,以拉出要在選項卡上顯示的相關內容:

public class TabViewModel : DependencyObject
{
      public object Content
      {
          get { return (object)GetValue(ContentProperty); }
          set
          {
              SetValue(ContentProperty, value);
          }
      }

}

這是TabControl:

<TabControl 
     ItemsSource={Binding MyCollectionOfTabViewModels}" 
     ItemContainerStyle="{StaticResource TabItemStyle}" />

這是風格

<Style TargetType="TabItem" x:Key="TabItemStyle">
     <Setter Property="Content" Value="{Binding Content}"/>
</Style>

我們正在創建一個usercontrol實例,並將TabViewModel的“Content”屬性設置為該屬性,以便userItrol顯示在TabItem的Content區域中。

MyCollectionOfViewModels.Add(new TabViewModel() 
{ 
     Content = new MyUserControl();
});

我的問題是, 我想允許添加到TabViewModel的Content屬性的MyUserControl(或其任何子控件)引發TabViewModel處理的事件

誰知道我會怎么做?

我們已經嘗試過使用RoutedEvents和RoutedCommands,但是無法讓任何東西100%工作並讓它與MVVM兼容。 我真的認為這可以通過RoutedEvent或RoutedCommand完成,但我似乎無法讓它工作。

注意:我已經刪除了一些相關的Prism特定代碼,但是如果你想知道我們為什么做這么愚蠢的事情,那是因為我們試圖通過使用Prism的RegionManager來保持控制不可知。

您可以向TabViewModel添加State屬性,並檢查DependencyPropertyChanged事件。

想象一下以下枚舉:

public enum TabViewModelState
{
    True,
    False,
    FileNotFound
}

然后將一個State屬性添加到此枚舉的TabViewModel中:

public static readonly DependencyProperty StateProperty =
    DependencyProperty.Register("State", typeof(TabViewModelState), typeof(TabViewModel), new PropertyMetadata(OnStateChanged));

private static void OnStateChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    TabViewModel viewModel= (TabViewModel)obj;

    //Do stuff with your viewModel
}

在控件中使用對此屬性的雙向綁定:

<CheckBox Checked="{Binding Path=State, Converter={StaticResource StateToBooleanConverter}, Mode=TwoWay}" />

最后但並非最不重要的是實現轉換器將轉換為控件所需的原始值..(在我的示例中boolean < - > TabViewModelState):

public class StateToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        TabViewModelState state = (TabViewModelState) value;
        return state == TabViewModelState.True;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool result = (bool) value;
        return result ? TabViewModelState.True : TabViewModelState.False;
    }
}

所以現在你有一個由UI管理的State屬性,並在你需要響應時拋出已更改的事件。

希望這可以幫助!

如果你在ViewModel上放一個命令並且只是從你的UserControl綁定它,那么無論如何它都會觸發。 你不必冒泡它,UserControl只會找到命令並使用它。

如果您的ViewModel上有一個委托命令“GoCommand”,那么您的UserControls按鈕綁定將如下所示:

<Button Command="{Binding GoCommand}" >Go</Button>

我經歷了同樣的思考過程,認為UserControl需要冒泡命令,但它不會 - 綁定只會在ViewModel上找到命令時自行掛鈎。

希望這有幫助,我不會錯過這一點! ;)

您應該看一下Marlon Grech的附加命令行為 ,它允許您將ViewModel命令附加到GUI事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM