使用枚举在XAML中访问数组 [英] Accessing an array in xaml with enums

查看:90
本文介绍了使用枚举在XAML中访问数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够通过使用枚举来访问XAML中ObservableCollection中的项目.

I would like to be able to access an item from an ObservableCollection in XAML by using an enum.

我可以绑定到ObservableCollection并通过以下方式指定XAML中的哪个项目:

I can bind to the ObservableCollection and specify which item in the XAML in the following way:

<Window x:Class="ArrayPropertyBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ArrayPropertyBinding"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MyViewModel />
    </Window.DataContext>
    <StackPanel>
        <CheckBox Content="First" IsChecked="{Binding FilterBy[0],Mode=TwoWay}"/>
        <CheckBox Content="Second" IsChecked="{Binding FilterBy[1],Mode=TwoWay}"/>
        <CheckBox Content="Thrid" IsChecked="{Binding FilterBy[2],Mode=TwoWay}"/>
        <CheckBox Content="Fourth" IsChecked="{Binding FilterBy[3],Mode=TwoWay}"/>
        <Button Content="Print" Click="Button_Click_1"/>
        <Button Content="SetFourthTrue" Click="Button_Click_SetFourthTrue"/>
    </StackPanel>
</Window>

视图模型如下所示

public class MyViewModel
{
    public enum Filters
    {
        First = 0,
        Second,
        Thrid,
        Fourth
    }

    private ObservableCollection<bool> _filterBy = new ObservableCollection<bool>() { false, false, false, false };
    public ObservableCollection<bool> FilterBy
    {
        get { return _filterBy; }
    }

    public void PrintFilters()
    {
        System.Diagnostics.Debug.Write("<<<<");
        foreach (bool b in _filterBy)
        {
            System.Diagnostics.Debug.Write(b);
            System.Diagnostics.Debug.Write(" ");
        }
        System.Diagnostics.Debug.WriteLine(">>>>");
    }

    public void SetFourthTrue()
    {
        FilterBy[(int)Filters.Fourth] = true;
    }
}

我希望能够这样编写XAML:

I would like to be able to write the XAML as this:

<CheckBox Content="First" IsChecked="{Binding FilterBy[Filters.First],Mode=TwoWay}"/>

任何指针或想法将不胜感激.

Any pointers or ideas would be greatly appreciated.

推荐答案

可能归结为

Probably boils down to custom binding path construction, as trying to enter an enum value directly does not appear to be possible.

语法应为:

{Binding Path={me:PathConstructor FilterBy[(0)], {x:Static myns:Filters.First}}}

(建议将枚举移出类,否则,如果我没有记错的话,则为myns:MyViewModel+Filters.First)

(Would recommend moving enums out of classes, otherwise it's myns:MyViewModel+Filters.First if i am not mistaken)

这篇关于使用枚举在XAML中访问数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆