user1294794
user1294794

Reputation: 1

Binding to the value of, value(which is again the property) of property in XAML

Background description: I have a custom control listbox, which shows values from a collection(say Person). Person class has Person_id, FirstName, LastName etc.

new Person(){
                Person_id = "T001",
                FirstName = "Fname1",
                LastName = "LName1"
            });

new Person()
            {
                Person_id = "T002",
                FirstName = "Fname2",
                LastName = "Lname2"
            });

There is a property named DefaultCategory in my custom control. This property defines which Person property to show in Listbox, e.g. in XAML if I will pass DefaultCategory = "FirstName" then my custom control listbox will contain items as "Fname1", "Fname2".

Requirement: I want to apply datatemplate from my custom control's resourceDictionary(Generic.XAML). I am doing like -

<DataTemplate x:Key="ComboItemTemplate">
    <TextBlock Text="{Binding Path=DefaultCategory}" FontStyle="Italic"/>
</DataTemplate>

Problem: When I run my application, the custom control listbox displays "FirstName" twice instead of displaying "Fname1", "Fname2"

Summary: I want to do binding with the value("Fname1") of value("FirstName") of property("DefaultCategory") Means instead of Binding valueof(DefaultCategory) I want to bind valueof(valueof(DefaultCategory)

Any kind of help is appreciated.

Upvotes: 0

Views: 74

Answers (1)

GazTheDestroyer
GazTheDestroyer

Reputation: 21241

You cannot do binding like this. You are binding the text block to the DefaultCategory property, which contains "FirstName", so your result is expected.

If you want to change bindings dynamically, you could use triggers in your template for each available field:

<DataTemplate x:Key="ComboItemTemplate">
    <TextBlock Name="DefaultText" FontStyle="Italic"/>

    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding Path=DefaultCategory}" Value="FirstName">
            <Setter TargetName="DefaultText" Property="Text" Value="{Binding FirstName}"/>
        </DataTrigger>

        <DataTrigger Binding="{Binding Path=DefaultCategory}" Value="LastName">
            <Setter TargetName="DefaultText" Property="Text" Value="{Binding LastName}"/>
        </DataTrigger>
    </DataTemplate.Triggers>

</DataTemplate>

Upvotes: 2

Related Questions