简体   繁体   中英

How to expose properties of a WPF DataTemplate?

I have a data template that I use in many pages, the data template contains a few buttons, I want to hide some of these buttons by triggers (I mean setting the IsEnabled Property of these buttons in the page where I use this DataTemplate).

In other words, I would even like to set in style triggers/setters a property 'ButtonXIsEnabled', 'ButtonYIsEnabled' as part of the DataTemplate settable from the ListBox where I use this DataTemplate.

I really hope I am clear enough, please leave comments for any further details.

Any discussion will be really appreciated! Thanks in advance.

Basically this depends on what object your using for your datatemplate. Instead of using some ButtonYIsEnabled, etcs. Try to use some words that fit better in to your domain model.

For example say you have a list of customers, and some of those customers have the ability to purchase discounted products. Then add a property to your Customer called CanPurchaseDiscountedProducts, and use that property in your DataTemplate

<DataTemplate TargetType="{x:Type local:Customer}">
  <!-- Other Items -->
  <Button Content="Purchase Discounted Products" x:Name="discounts" Visibility="Hidden" />
  <DataTemplate.Triggers>
    <DataTrigger Binding="{Binding CanPurchaseDiscountedProducts}" Value="True">
      <Setter TargetName="discounts" Property="Visibility" Value="Visible"/>
    </DataTrigger>
  </DataTemplate.Triggers>
</DataTemplate>

A WPF data template is a view of a certain object type... how you want an instance of ObjectTypeX to look. The data template can bind to properties on the underlying instance.

So if you have a ButtonXIsEnabled property on your instance, you can bind the corresponding Button's Visibility property to the instance property. The button would be shown or hidden based on the value in the underlying object.

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