开发者

Data Binding inside another Data Bound Control - Depending on the current item

开发者 https://www.devze.com 2022-12-10 13:04 出处:网络
Let\'s say that you have a List that looks like the following public List<Person> Persons { get; set; }

Let's say that you have a List that looks like the following

public List<Person> Persons { get; set; }

You set an ItemSource on a ListBox to get the data from Persons and for each person in that list, you want to select other items, depending on the social security number.

It is not an option to store the data in the Person, so the Data has to be fetched once the Person is processed in the list开发者_如何学Python.

This will end up looking somewhat like this om XAML

<ListBox Name="myListBox">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Label Content="{Binding Name}"/>
                <ComboBox ItemsSource="{Binding MyOtherData}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Now, I want MyOtherData to be a Method which will return a set of data, depending on the current person, so I would just like to have a Method, takin an argument like the social security-number.

How could this look?

I am kind of new to the WPF - XAML stuff and if this is a design flaw, please suggest other solutions on that aswell.


The WPF way to do this is to use an Converter. Do a class that Implements IValueConverter, and add the Attribute ValueConversion to it. In the attribute you have to state from what type you convert to which, int (security number isn't probably an int but...) to probably some kind of list say an String array:

[ValueConversion(typeof(int), typeof(string[]))]
public class GetThatData : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
       return new string[]{"just","for","test"};
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Second you need to import the namespace (if you haven't already done that):

xmlns:local="clr-namespace:NamespaceWhereTheClassIs"

Third, create an object of the class:

<Window.Resources>
    <local:GetThatData x:Key="otherData" />
</Window.Resources>

And last apply the converter whit he value:

 <ComboBox ItemsSource="{Binding Path=SSN, Converter={StaticResource otherData}}" />

just pure WPF magic, hope you can make it work

0

精彩评论

暂无评论...
验证码 换一张
取 消