简体   繁体   中英

WPF MVVM TextBlock binding to string in a class DependencyProperty

In my application I have a list of members in a DataGrid , and when a member is selected a member profile is populated with their details. The member profile consists of 10+ TextBlocks with each text value bound to an individual DependencyProperty (DP) of type string .

The generated member list is a List<MEMBERINFO> , and the SelectedMember DP is MEMBERINFO type.

public partial class MEMBERINFO
{
    public GD_MEMBERDETAILS MEMBERDETAILS { get; set; }
    public List<GD_ADDRESSDETAILS> ADDRESSDETAILS { get; set; }
    public List<GD_VESSELDETAILS> BOATDETAILS { get; set; }
    public GD_MEMBERSHIPS MEMBERSHIP { get; set; }
    public List<string> FAMILYMEMBERS { get; set; }
}

Currently, when a member is selected in the DataGrid , SelectedMember values are assigned to individual DependencyProperties for display in the member profile eg

MemberName = SelectedMember.MEMBERINFO.MEMBER_NAME;

While this works, I feel like there should be a neater way to do this, seeing as I already have all the info I need in SelectedMember . So rather than having 10+ string DependencyProperties and assigning their values from SelectedMember , is there a way to have all the TextBlocks inside a container with an ItemsSource bound to SelectedMember and assign bind the text to the properties within SelectedMember ? So in the same way that you do with a DataGrid? I know that ListView and ListBox also have ItemsSource but my member profile is not a list, I just want a simple container that doesn't have any inherent functionality in the way that DataGrids and ListViews/Box do.

Note: In another application with a similar problem I managed to manipulate a DataGrid to remove all it's inherent DataGrid functionality and display multiple textblocks in a single cell so that I could use its ItemsSource. But this was quite a pain to do, so again I feel like there should be an easier way!

Can't you just bind the TextBlock 's directly to the source properties?:

<ItemsControl ...>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding DataContext.SelectedMember.MEMBERINFO.MEMBER_NAME, 
                        RelativeSource={RelativeSource AncestorType=ItemsControl}}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

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