简体   繁体   English

WPF:将背景保留在边框中

[英]WPF: Keep background in Border

I have a treeview with items that can be colored differently. 我有一个树形图,其中的项目可以有不同的颜色。 Like this 像这样

边界问题

As you can see the background is bigger than the border. 如您所见,背景比边框大。 How can I keep the background color inside the border? 如何将背景颜色保留在边框内?

This is the relevant code: 这是相关代码:

<DataTemplate DataType="{x:Type models:MyClass}">
    <Border BorderBrush="Black" 
            HorizontalAlignment="Stretch" 
            BorderThickness="1" 
            Margin="2" >                
        <TextBlock Text="{Binding Path=Name}" 
                   Foreground="Black" 
                   Width="{Binding Path=ActualWidth, ElementName=MyTreeView, Mode=OneWay}" 
                   Background="{Binding Background}" 
                   Margin="3" />
    </Border>
</DataTemplate>

To set the background I use a property in my TextBlock 要设置背景,我在TextBlock中使用了一个属性

Background="{Binding Background}" 

In my ViewModel I set the background of the TreeViewItem like this 在我的ViewModel中,我像这样设置TreeViewItem的背景

var item = new TreeViewItem { Header = myClassInstance };
item.Background = Brushes.Blue;

which led to the problematic overlapping background color. 这导致了有问题的重叠背景颜色。

I changed it to set the background not to the TreeViewItem but to my class instance in the item. 我将其更改为将背景设置为不是TreeViewItem而是设置为项中的类实例。 So I changed the above 2 lines to 所以我将上面两行更改为

var item = new TreeViewItem { Header = myClassInstance };
myClassInstance.Background = Brushes.Blue;

and it works as expected. 它按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM