首页 > 解决方案 > 具有统一 BorderThickness 的边框无法绑定 BorderBrush 颜色

问题描述

最小、完整、可验证的示例(.NET Framework 4.0+):

MainWindowViewModel.cs

namespace MCVBorderTest
{
    public class MainWindowViewModel
    {
        public string BorderColor { get { return "Red"; } }
    }
}

主窗口.xaml

<Window x:Class="MCVBorderTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Border BorderThickness="1">
        <Border.BorderBrush>
            <SolidColorBrush Color="{Binding BorderColor}" />
        </Border.BorderBrush>
    </Border>
</Window>

主窗口.xaml.cs

using System.Windows;

namespace MCVBorderTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

应用程序.xaml

<Application x:Class="MCVBorderTest.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:MCVBorderTest">
</Application>

应用程序.xaml.cs

using System.Windows;

namespace MCVBorderTest
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            new MainWindow() { DataContext = new MainWindowViewModel() }.Show();
        }
    }
}

应用程序配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
</configuration>

问题:

运行应用程序会打开一个窗口,但边框没有颜色。调试输出包含以下消息:

System.Windows.Data 错误:2:找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。绑定表达式:路径=边框颜色;数据项=空;目标元素是“SolidColorBrush”(HashCode=8990007);目标属性是“颜色”(类型“颜色”)

将 BorderThickness 更改为非统一值,例如 0,1,1,1,将导致边框接收其预期颜色,并且在 Debug 输出中没有绑定错误。

问题:

为什么 BorderBrush 的颜色绑定会这样?

标签: c#.netwpfxaml

解决方案


这对我来说看起来像是一个真正的错误,请注意边框画笔和背景之间的不同行为:

<Border BorderThickness="10">
    <Border.BorderBrush>
        <SolidColorBrush Color="{Binding BorderColor}" />
    </Border.BorderBrush>
    <Border.Background>
        <SolidColorBrush Color="{Binding BorderColor}" />
    </Border.Background>
</Border>

一个明显的解决方法是给您的窗口 ax:Name ("_this") 并通过 DataContext 显式绑定:

<SolidColorBrush Color="{Binding ElementName=_this, Path=DataContext.BorderColor}" />

可悲的是,通过 RelativeSource 绑定似乎也表现出这个问题。


推荐阅读