1
我基本上有一個ContentControl,它具有Border作爲內容的女巫也有TextBlock作爲內容。我想要的是例如TextBlock的Foreground Brush被綁定到父ContentControl的依賴項屬性...我被卡在這裏,我不知道如何解決這個問題。將依賴項屬性綁定到代碼中的子元素
public class NumberRollItem : ContentControl
{
public int Index { get; set; }
public int AnimationIndex { get; set; }
public Brush ItemForeground
{
get { return (Brush)GetValue(ItemForegroundProperty); }
set { SetValue(ItemForegroundProperty, value); }
}
public static readonly DependencyProperty ItemForegroundProperty =
DependencyProperty.Register("ItemForeground", typeof(Brush), typeof(NumberRollItem), new PropertyMetadata(new SolidColorBrush(Colors.White)));
public Brush ItemBackground
{
get { return (Brush)GetValue(ItemBackgroundProperty); }
set { SetValue(ItemBackgroundProperty, value); }
}
public static readonly DependencyProperty ItemBackgroundProperty =
DependencyProperty.Register("ItemBackground", typeof(Brush), typeof(NumberRollItem), new PropertyMetadata(new SolidColorBrush(Colors.Black)));
public double ItemFontSize
{
get { return (double)GetValue(ItemFontSizeProperty); }
set { SetValue(ItemFontSizeProperty, value); }
}
public static readonly DependencyProperty ItemFontSizeProperty =
DependencyProperty.Register("ItemFontSize", typeof(double), typeof(NumberRollItem), new PropertyMetadata(45d));
public NumberRollItem(char c, int index)
{
this.Index = index;
string text = ""; text += c;
HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;
Content = new Border()
{
Background = ItemBackground, // Background bound to ItemBackground but how??
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
Child = new TextBlock()
{
FontSize = 45,
Text = text,
Foreground = ItemForeground,
},
};
}
}
其實有在Windows的手機,但由於沒有RelativeSourceMode.FindAncestor反正。 –
@ElMarchewko哦,我忘了這是WP。我已經更新了適用於Windows手機的答案。基本上只需要將'RelativeSource'綁定切換到一個簡單的''ElementName'',如更新後的答案所示。我已經檢查過它在模擬器上正常工作。 – Viv