TextBlock我希望在 WPF中插入一個彩色正方形(帶邊框) 。正方形的顏色需要動態設定,因此理想情況下這應該發生在代碼隱藏中,而不是 XAML。
我猜最好的方法是使用 a InlineUIContainer,但我不知道如何定位 aRectangle以使其與文本對齊,并根據字體大小調整大小。
到目前為止,我有:
Color myColor = GetMyColor();
TextBlock textBlock = new TextBlock();
textBlock.Inlines.Add(new Run("My color: "));
// Attempt with a Canvas and Rectangle
Canvas canvas = new Canvas();
canvas.Children.Add(new Rectangle() { Height = 6, Width = 6, Fill = new SolidColorBrush(color.Value) });
textBlock.Inlines.Add(new InlineUIContainer(canvas));
// Hacky version that looks terrible
textBlock.Inlines.Add(new Run(" ") { Background = new SolidColorBrush(myColor) });
這里的問題是它Rectangle是從文本基線創建的,下垂。我希望它相對于文本垂直居中,正方形(即縱橫比為 1),并且理想情況下自動調整為字體大小。
我想知道 aViewbox是否有用,或者某些VerticalAlignment屬性組合,但我無法使它們起作用。任何建議將不勝感激。
uj5u.com熱心網友回復:
根據您想要的正方形大小,您可以嘗試使用 Unicode 字符 0x25A0 或 0x25AA。
這是在 Xaml 中定義的示例,但您也可以在后面的代碼中實作相同的效果。
<TextBlock FontFamily="Segoe UI">
<Run Text="ABC" />
<Run Foreground="Red" Text="■" />
<Run Foreground="Green" Text="▪" />
</TextBlock>
<TextBlock FontFamily="Tahoma">
<Run Text="ABC" />
<Run Foreground="Red" Text="■" />
<Run Foreground="Green" Text="▪" />
</TextBlock>

請注意,與常規字母的高度相比,不同的字體系列以不同的比例呈現這些字符。
uj5u.com熱心網友回復:
您可以使用 aContentControl和 a DataTemplate。
A UserControlor custom ControlorContentControl也是一個很好的解決方案,特別是如果您想添加一個行為。
以下示例使用 aContentControl和 a在文本旁邊DataTemplate居中顯示 a ,其中形狀的顏色和文本是動態值。Rectangle形狀的大小是相對于FontSize應用到的ContentControl。可以通過在 上設定 a或將 a 附加到 的系結
來調整形狀的最終大小:MarginViewboxIValueConverterHeightViewbox
主視窗.xaml
<Window>
<Window.Resources>
<DataTemplate x:Key="DataModelTemplate"
DataType="{x:Type DataModel}">
<DockPanel HorizontalAlignment="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=HorizontalContentAlignment}">
<TextBlock x:Name="TextLabel"
FontSize="{Binding RelativeSource={RelativeSource AncestorType=ContentControl}, Path=FontSize}"
Text="{Binding TextValue}"
VerticalAlignment="Center" />
<Viewbox Height="{Binding ElementName=TextLabel, Path=ActualHeight}"
Margin="8"
Stretch="Uniform">
<Rectangle Width="10"
Height="10"
Fill="{Binding Color}" />
</Viewbox>
</DockPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ContentControl x:Name="TextControl1"
ContentTemplate="{StaticResource DataModelTemplate}"
FontSize="50" />
<ContentControl x:Name="TextControl2"
ContentTemplate="{StaticResource DataModelTemplate}"
FontSize="20" />
</StackPanel>
</Window>
主視窗.xaml.cs
partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.TextControl1.Content = new DataModel("@Test 1", Brushes.Yellow);
this.TextControl2.Content = new DataModel("@Test 2", Brushes.Red);
}
}
資料模型.cs
class DataModel : INotifyPropertyChanged
{
public DataModel(string textValue, Brush color)
{
this.TextValue = textValue;
this.Color = color;
}
public string TextValue { get; }
public Brush Color { get; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452451.html
