![](/img/trans.png)
[英]How do I implement a WPF control with its own DataTemplate DependencyProperty?
[英]How do I implement a DependencyProperty in an ItemsControl
我有一個用戶控件(DeckList),其中包含一個ItemsControl,該控件僅在網格中並排顯示3個Label。
<ItemsControl x:Class="OpponentDeck.DeckList"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:OpponentDeck"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="FrameworkElement.Margin" Value="0,0,0,0" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<!--<Rectangle Grid.Column="0" Fill="{Binding Card.Background}" Height="34" Width="217" />-->
<Label x:Name="lblCost" Grid.Column="0" Content="{Binding Card.Cost}" Foreground="LimeGreen" HorizontalContentAlignment="Center" Background="Black" FontSize="12" FontFamily="Tekton Pro" VerticalAlignment="Center" Margin="0" HorizontalAlignment="Center"/>
<Label x:Name="lblCard" Grid.Column="1" Content="{Binding Card.Name}" Foreground="{Binding TextColor, ElementName=lblCard}" HorizontalContentAlignment="Center" Background="Black" FontSize="12" FontFamily="Tekton Pro" VerticalAlignment="Center" Margin="0" HorizontalAlignment="Left"/>
<Label x:Name="lblQty" Grid.Column="2" Content="{Binding Qty}" Foreground="LimeGreen" HorizontalContentAlignment="Center" Background="Black" FontSize="12" FontFamily="Tekton Pro" VerticalAlignment="Center" Margin="0" HorizontalAlignment="Center"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
該用戶控件(DeckList)在另一個添加到主窗口的UserControl(UI)中使用。 該用戶控件由一個並排帶有2個DeckList的堆棧面板組成。 在定義UI.xaml時,我想通過設置屬性來指定標簽的顏色。 我有這個標記
<controls1:DeckList TextColor="LimeGreen" x:Name="playableCards" Width="150"></controls1:DeckList>
DeckList的代碼隱藏具有DependencyProperty和屬性Get / Set
public static readonly DependencyProperty TextColorProperty = DependencyProperty.Register("TextColor", typeof(SolidColorBrush), typeof(DeckList), new PropertyMetadata(new SolidColorBrush(Colors.HotPink)));
public System.Windows.Media.Brush TextColor {
get { return (System.Windows.Media.Brush)GetValue(TextColorProperty); }
set { SetValue(TextColorProperty, value); }
}
我很確定問題與綁定有關,但是對於我一生來說,我不知道該如何使它生效。
有人可以幫忙嗎?
你有
<Label x:Name="lblCard" Foreground="{Binding TextColor, ElementName=lblCard}" .../>
由於Label沒有TextColor
屬性,因此無法使用。
為了使用DeckList控件的TextColor
屬性,請使用
Foreground="{Binding TextColor, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.