简体   繁体   English

WPF使用元素属性作为索引值绑定到单个列表项

[英]WPF Binding To Single List Item Using Element Property As Index Value

I'm trying to bind to a single item from a collection but I need to be able to pass in a value from the element as the index. 我试图绑定到集合中的单个项目,但我需要能够将元素中的值作为索引传递。 Below is a sample of what I'm trying to accomplish. 以下是我要完成的示例。

ViewModel 视图模型

public Dictionary<string, string> ListOfString = new Dictionary<string, string>
{ 
    {"0", "TextToDisplay" }
};

View 视图

<TextBox Tag="0" Text="{Binding ListOfString[Self.Tag]}" />

I'm not sure how to get the value of TextBox.Tag and pass it to ListOfString 我不确定如何获取TextBox.Tag的值并将其传递给ListOfString

You could use a MultivalueConverter in which you will pass the ListOfStrings Dictionary and the Tag property of the TextBox like so: 你可以使用一个MultivalueConverter中,你将通过ListOfStrings DictionaryTag的财产TextBox ,如下所示:

  <Window.Resources>
    <ns:ValuFromDicConverter x:Key="ValuFromDicConverter"/>
</Window.Resources>
<Grid>
    <TextBox Tag="0" x:Name="tb">
        <TextBox.Text>
            <MultiBinding Converter="{StaticResource ValuFromDicConverter}">
                <Binding Path="ListOfString"/>
                <Binding ElementName="tb" Path="Tag"></Binding>
            </MultiBinding>
        </TextBox.Text>
    </TextBox>
</Grid>

the converter will simply get the corresponding value in the Dictionary : 转换器将简单地在Dictionary获得相应的值:

 public class ValuFromDicConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values == null) return null;
        return (values[0] as Dictionary<string, string>)[values[1].ToString()];

    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

and don't forget to define your dictionary as a property and set the DataContext 并且不要忘记将字典定义为属性并设置DataContext

    private Dictionary<string, string> _listOfString = new Dictionary<string, string>
    { 
        {"0", "TextToDisplay" }
    };


    public Dictionary<string, string> ListOfString
    {
        get
        {
            return _listOfString;
        }

        set
        {
            if (_listOfString.Equals(value))
            {
                return;
            }

            _listOfString = value;

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM