无法使用Click或Command来处理动态创建的MenuFlyOutItems

时间:2016-04-21 01:06:46

标签: c# xaml mvvm event-handling treeview

我有一个TreeView,里面有几层。每个项目都填充了一个MenuFlyoutItem的ObservableCollection,具体取决于它在运行时动态创建的对象类型。重要的是要注意这是在Windows 10 Universal App中,因此任何解决方案或建议都需要与它们相关。

TreeView对象的创建方式如下:

public TreeViewItemModel(object thing)
    {
        MenuItems.Clear();
        if (thing.GetType() == typeof (Space))
        {
            var space = (Space)thing;
            var parentName = string.Empty;
            if (space.Parent != null)
            {
                parentName = space.Parent.Name;
            }
            Name = space.Name;
            ParentName = parentName;
            Id = space.Id;
            var addDeviceMenuItem = new MenuFlyoutItem { Name = "AddDevice", Text = "Add Device"};
            var addSensorMenuItem = new MenuFlyoutItem { Name = "AddSensor", Text = "Add Sensor" };
            var addSpaceMenuItem = new MenuFlyoutItem { Name = "AddSpace", Text="Add Space"};
            var updateMenuItem = new MenuFlyoutItem { Name = "UpdateSpaceInfo", Text = "Update Space Info" };
            var deleteMenuItem = new MenuFlyoutItem { Name = "DeleteSpace", Text = "Delete Space" };
            var items = new ObservableCollection<MenuFlyoutItem> {addDeviceMenuItem, addSensorMenuItem,addSpaceMenuItem, updateMenuItem, deleteMenuItem};
            MenuItems = items;
            Children = new ObservableCollection<TreeViewItemModel>(space.Children.Select(s => new TreeViewItemModel(s)).Union(space.Devices.Select(d => new TreeViewItemModel(d)).Union(space.Sensors.Select(sensor => new TreeViewItemModel(sensor)))));
        }

        else if (thing.GetType() == typeof (Device))
        {
            var device = (Device) thing;
            var parentName = device.Space.Name;
            Name = device.Name;
            ParentName = parentName;
            Id = device.Id;
            var addMenuItem = new MenuFlyoutItem { Name = "AddSensor", Text = "Add Sensor" };
            var updateMenuItem = new MenuFlyoutItem { Name = "UpdateDeviceInfo", Text = "Update Device Info" };
            var deleteMenuItem = new MenuFlyoutItem { Name = "DeleteDevice", Text = "Delete Device" };
            var items = new ObservableCollection<MenuFlyoutItem> { addMenuItem, updateMenuItem, deleteMenuItem };
            MenuItems = items;
            Children = new ObservableCollection<TreeViewItemModel>(device.Sensors.Select(s => new TreeViewItemModel(s)));
        }

        else if (thing.GetType() == typeof(Sensor))
        {
            var sensor = (Sensor) thing;
            var space = sensor.Space.Name ?? string.Empty;
            var device = sensor.Device;
            ParentName = device == null ? "No Matching Device" : device.Name;
            Name = sensor.Id.ToString();
            Id = sensor.Id;
            ParentName = space;
            var updateMenuItem = new MenuFlyoutItem { Name = "UpdateSensorInfo", Text = "Update Sensor Info" };
            var deleteMenuItem = new MenuFlyoutItem { Name = "DeleteSensor", Text = "Delete Sensor" };
            var items = new ObservableCollection<MenuFlyoutItem> {updateMenuItem, deleteMenuItem};
            MenuItems = items;
            Children = null;
        }

    }

xaml中的My TreeView如下所示:

<controls:TreeView x:Name="TreeViewList" Grid.Row="0" Margin="5" ItemsSource="{Binding TreeSpaces}">
        <controls:TreeView.ItemTemplate>
            <DataTemplate>
                <data:DataTemplateExtensions.Hierarchy>
                    <data:HierarchicalDataTemplate ItemsSource="{Binding Children}"/>
                </data:DataTemplateExtensions.Hierarchy>
                <Button x:Name="TreeButton" Content="{Binding Name}" BorderThickness="0" BorderBrush="Transparent" Background="Transparent">
                    <Button.Flyout>
                        <Flyout common:BindableFlyout.ItemsSource="{Binding MenuItems}">
                            <common:BindableFlyout.ItemTemplate>
                                <DataTemplate>
                                    <MenuFlyoutItem Text="{Binding Text}"/>
                                </DataTemplate>
                            </common:BindableFlyout.ItemTemplate>
                        </Flyout>
                    </Button.Flyout>
                </Button>
            </DataTemplate>
        </controls:TreeView.ItemTemplate>
    </controls:TreeView>

我似乎无法通过任何形式的事件处理来触发MenuFlyoutItem工作。

最初我尝试<MenuFlyoutItem Name={Binding Name} Text={Binding Text} view:EventHandlers.Attach="Click"/>这样可以解决自定义MVVM实现将事件附加到ViewModel处理程序的问题。在幕后,我们的附加机制获取对象的名称并与Click相关联,因此如果名称为SaveButton:public void SaveButton_Click(object sender, RoutedEventArgs e),它将在视图模型中看起来像这样。现在,我通常从来没有遇到过这个问题,但我认为这个问题可能源于试图将MenuBinding用于MenuFlyoutItem的Name而不是传统的x:Name="blah blah";然而,尝试这也不起作用。我想也许这可能是因为它是一个MenuFlyoutItem而不是每个说法的按钮,所以我尝试将它改为<Button/>所有相应的东西,这也不起作用。所以,我回到了MenuFlyoutItem并尝试使用Command属性。即Command="{Binding MenuItemSelected}"。然后在我的ViewModel中,我有以下内容:

public RelayCommand<object> MenuItemSelected { get; internal set; }
public TreeViewPageVM()
{
    MenuItemSelected = new RelayCommand<object>(TestAction);
}

private void TestAction(object sender)
{

}

这也不起作用......所以,尽管我想使用MVVM,但我还是通过使用传统的<MenuFlyoutItem x:Name="MenuItem" Text="{Binding Text} Click="MenuItem_Clicked"和相应的private void MenuItem_Clicked(object sender, RoutedEventArgs e)处理程序来尝试代码。令我惊讶的是,这也没有用。所以,我不确定是什么导致了我的MenuFlyoutItem生成事件的能力的抑制,但是对此的一些帮助将不胜感激。

理想情况下,无论是点击事件还是命令事件,我都想在我的ViewModel中处理它,我希望命令或点击事件能够抓住生成的按钮上的Content弹出菜单(在事件的后期处理期间我需要它)以及被点击的MenuFlyoutItem中的Text

以防万一需要进一步明确: 我会在树中有像这样的对象

----Object1
--------SubObject

如果我点击SubObject(在这种情况下是一个附有弹出窗口的Button),会出现一个弹出菜单,其中包含以下选项:添加,更新,删除。当我单击/点击添加例如,我需要我的结束事件处理程序或命令以了解SubObject(特别是它的内容,因为它是一个按钮)和ClickFedoutItem(特别是Text属性所以我知道我是否需要添加,更新或删除)。

2 个答案:

答案 0 :(得分:1)

上面给出的快速正确的答案(即在您创建MenuFlyoutItem的相同代码中添加Command)会导致您的代码违反MVVM模式,因为您在ViewModel中创建了View的控件,所以更好的解决方案是

1)为Flyout实现ViewModel

public class DeviceViewModel
    {
        public string Name { get; set; }

        internal int treeNum;

        private DelegateCommand flyoutCommand;
        public ICommand FlyoutCommand
        {
            get
            {
                if (flyoutCommand == null)
                {
                    flyoutCommand = new DelegateCommand((parameter) => FlyoutLogic(), (parameter) => CanFlyout());
                }
                return flyoutCommand;
            }
        }

        private bool CanFlyout()
        {
            return true;
        }

        private void FlyoutLogic()
        {
            Debug.WriteLine("here we go " + Name + treeNum);
        }
    }

2)实例化ViewModel

                    var addDeviceMenuItem = new DeviceViewModel { Name = "AddDevice", treeNum = _itemId  };
                    var addSensorMenuItem = new DeviceViewModel { Name = "AddSensor", treeNum = _itemId  };
                    var addSpaceMenuItem = new DeviceViewModel { Name = "AddSpace", treeNum = _itemId  };
                    var updateMenuItem = new DeviceViewModel { Name = "UpdateSpaceInfo", treeNum = _itemId  };
                    var deleteMenuItem = new DeviceViewModel { Name = "DeleteSpace", treeNum = _itemId  };
                    var items = new ObservableCollection<DeviceViewModel> { addDeviceMenuItem, addSensorMenuItem, addSpaceMenuItem, updateMenuItem, deleteMenuItem };
                    tree.Add(
                        new TreeItemModel
                        {
                            Branch = b,
                            Depth = d,
                            Text = "Item " + _itemId++,
                            Children = BuildTree(d, b),
                            MenuItems = items
                });

ObservableCollection<DeviceViewModel> _menuItems;
public ObservableCollection<DeviceViewModel> MenuItems
{
    get { return _menuItems; }
    set { this.SetProperty(ref _menuItems, value); }
}

3)最后将XAML绑定到ViewModel

<controls:TreeView x:Name="TreeViewList" Grid.Row="0" Margin="5" ItemsSource="{Binding TreeItems}">
    <controls:TreeView.ItemTemplate>
        <DataTemplate>
            <data:DataTemplateExtensions.Hierarchy>
                <data:HierarchicalDataTemplate ItemsSource="{Binding Children}"/>
            </data:DataTemplateExtensions.Hierarchy>
            <Button
                x:Name="TreeButton" Content="{Binding Text}" BorderThickness="3" Background="Transparent">
                <Button.Flyout>
                    <Flyout common:BindableFlyout.ItemsSource="{Binding MenuItems}">
                        <common:BindableFlyout.ItemTemplate>
                            <DataTemplate>
                                <MenuFlyoutItem Text="{Binding Name}" Command="{Binding FlyoutCommand}"/>
                            </DataTemplate>
                        </common:BindableFlyout.ItemTemplate>
                    </Flyout>
                </Button.Flyout>
            </Button>
        </DataTemplate>
    </controls:TreeView.ItemTemplate>
</controls:TreeView>

答案 1 :(得分:0)

您可以在创建MenuFlyoutItem的相同代码中添加命令,以便

 var addDeviceMenuItem = new MenuFlyoutItem { Name = "AddDevice", Text = "Add Device"
 };
 addDeviceMenuItem.Command = AddDeviceCommand;