简体   繁体   中英

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

You could use a MultivalueConverter in which you will pass the ListOfStrings Dictionary and the Tag property of the TextBox like so:

  <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 :

 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

    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;

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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