我基本上得到了一个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,
},
};
}
}
答案 0 :(得分:0)
针对WP进行了更新
如果您通过代码执行所有操作,也可以在代码中创建Binding,
类似的东西:
public NumberRollItem(char c, int index)
{
this.Index = index;
string text = ""; text += c;
// Giving This control a Name to later use for Binding
string thisControlName = "NumberItem";
Name = thisControlName;
HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;
var tBlock = new TextBlock()
{
FontSize = 45,
Text = text
};
var binding = new Binding
{
ElementName = thisControlName,
Path = new PropertyPath("ItemForeground")
};
tBlock.SetBinding(TextBlock.ForegroundProperty, binding);
Content = new Border()
{
Background = ItemBackground,
HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
VerticalAlignment = System.Windows.VerticalAlignment.Stretch,
Child = tBlock,
};
}
您使用此代码执行的操作是:
在NumberRollItem
的构造函数中,您创建一个Binding
,ElementName
指向NumberRollItem
类,并将绑定分配给TextBlock.ForegroundProperty
。因此,这将限制它们允许ItemForeground
的任何未来更改也影响TextBlock.Foreground
。
不确定为什么你采用这种方法而不是xaml Style
路线,但是对你来说无论如何:)