[英]Adding a WPF UserControl programmatically has no style
我正在尝试创建一个类似按钮的UserControl,它由边框和标签组成。 直接在MainWindow的XAML中添加此UserControl时,它可以正确呈现(将其放在WrapPanel中),但是如果我以编程方式添加它,则看起来根本不一样。 没有边框,没有背景色,标签的文本大小不正确,文本颜色也是如此。
这是我的用户控件:
<UserControl x:Class="Jishi.SonosPartyMode.UserControls.Player"
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"
mc:Ignorable="d"
d:DesignHeight="150" d:DesignWidth="300"
Width="200"
Height="100">
<Border BorderBrush="#086EAA" CornerRadius="8,8,8,8" BorderThickness="4" Margin="15" Padding="15px" VerticalAlignment="Center" Background="#0A4069">
<Label Name="PlayerName" TextElement.Foreground="White" TextElement.FontSize="20px">asdasdasd</Label>
</Border>
</UserControl>
添加它时,我只是这样调用它:
var button = new Player { Content = player.Properties.RoomName, DataContext = player.Properties.UDN };
PlayerList.Children.Add( button );
PlayerList是实际的WrapPanel,Player是我的UserControl。 我尝试查找有关此的信息,但未找到任何信息。 如果您可以采用其他方法,请提出建议。 我想要的是一个带有一些圆角的可单击区域,该圆角可以包含文本(一个或多个行)。
我可以通过编程方式应用样式,但是不保留在xaml中为UserControl定义的样式(边框,边距,颜色等)。
首先,您不需要为此创建自定义控件,您可以轻松地
var button = new Border { *border properties*, Content = new Lable {Content="dfsdfsdfsd"}};
并且如果您使用PlayerList.Children.Add(button); 然后将其添加到Wrappanel的末尾,并在XAML代码中将其添加为最后一个元素(也许不是)。
最后一个想法是,您在测试XAML时会丢失一些在XAML中添加的属性(例如,匹配度,边距等)。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.