如何在通过代码创建背景后以编程方式将边框的背景和边框刷与标签背景绑定



我在 c# wpf
中通过代码创建了一个边框和一个标签,我想创建一个数据绑定,用于BackgroundBorderBrush带有标签Background的边框

这是代码

void creatlbl()
{
Border b = new Border();
b.Name = "b11";
b.Margin = new Thickness(300,17,0,419);
b.Height = 32;
b.CornerRadius = new CornerRadius(5);
b.Width = 181;
b.BorderThickness = new Thickness(2);
b.HorizontalAlignment = HorizontalAlignment.Left;
lgingrd.Children.Add(b); //
Label l = new Label();
l.Name = "l111";
l.Content = "l111";
l.Height = 28;
l.Width = 177;
l.Foreground = (Brush)bc.ConvertFrom("#FF346D80");
l.FontSize = 20;
l.Background = (Brush)bc.ConvertFrom("#FF9AB426");
l.HorizontalContentAlignment = HorizontalAlignment.Center;
l.Padding = new Thickness(0,0,0,0);
l.Visibility = Visibility.Visible;
b.Child = l;
// here i want to set binding for border 
// the  background and borderbrush of border equal to the background of label 
}

我为 XAML 中的按钮做了同样的事情,就像这样

<Border x:Name="brdbt" Margin="120,58,0,378"
BorderBrush="{Binding Background, ElementName=bt}" <!--this is the binding which i want-->
Height="32"
CornerRadius="5"
Width="181"
BorderThickness="2"
HorizontalAlignment="Left" Background="{Binding Background, ElementName=bt}">
<Button x:Name="bt" Content="btntxt" HorizontalAlignment="Left" VerticalAlignment="Top" Height="28" Width="177" Click="bt_click" BorderBrush="{x:Null}" Foreground="#FFE8EEF0" FontSize="20" Padding="1,-1,1,1" MouseEnter="bt_mcentr" MouseLeave="bt_mclv" Background="#FFE62828"/>
</Border>

有没有办法在 c# 代码中对我上面提到的 c# 代码中的边框和标签进行上述 xaml 类型绑定?

创建Binding使用标签l作为源(new Binding("Background") { Source = l })的路径"Background"的对象,并将该绑定分配给目标属性:Border.Background和Border.BorderBrush

BindingOperations.SetBinding(b, BackgroundProperty,  new Binding("Background") { Source = l });
BindingOperations.SetBinding(b, BorderBrushProperty, new Binding("Background") { Source = l });

您知道在 xaml 中创建整个代码块会更简单。 只需用密钥将其包装在数据模板中即可。 在您的代码中,创建一个内容演示器,将数据作为内容提供给它, 并为其提供您的数据模板,因为它是内容模板值:

ContentPresenter cp = new ContentPresenter();
cp.Content = (?)
cp.ContentTemplate = Application.Current.Resources.Find("DataTemplateKey") as DataTemplate;

最新更新