簡體   English   中英

WPF:使用綁定屬性自定義數據模板

[英]WPF: Customize a datatemplate using a binding property

我是WPF的新手。 我有一個ListBox,我想在其中設置項目的模板(我稱其為Person)。 將使用TextBlock。 此人必須公開屬性:“前景”和“ IsOnline”。 如果“ IsOnline”為true,則將使用人員的“ Foreground”屬性,否則為“ Gray”。 就這樣。 我的第一個模板是:

<DataTemplate x:Key="UnselectedPersonTemplate" DataType="{x:Type o:Person}">
    <TextBlock Text="{Binding Path=Name}" Foreground="{Binding Path=Foreground}" Margin="1">
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding Path=IsOnline}" Value="False">
                <Setter Property="TextBlock.Foreground" Value="Gray" />
            </DataTrigger>
        </DataTemplate.Triggers>
</DataTemplate>

當然,這是行不通的。 沒有例外,但也不是預期的結果。 然后,我嘗試將觸發器用於TextBlock,但是會有一個例外,我不能為此使用DataTriggers(僅EventTriggers)。

感謝您的任何建議! :)

給您的TextBlock命名,並將設置器的TargetName屬性設置為該名稱。

<DataTemplate x:Key="UnselectedPersonTemplate" DataType="{x:Type o:Person}">
    <TextBlock x:Name="tb" Text="{Binding Path=Name}" 
          Foreground="{Binding Path=Foreground}" Margin="1" />
    <DataTemplate.Triggers>
       <DataTrigger Binding="{Binding Path=IsOnline}" Value="False">
          <Setter TargetName="tb" Property="Foreground" Value="Gray" />
       </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM