最小、完整、可验证的示例(.NET Framework 4.0+):
主窗口视图Model.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();
}
}
}
App.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>
App.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();
}
}
}
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
问题:
运行应用程序将导致窗口打开,但边框没有颜色。Debug输出有以下消息:
System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。BindingExpression:Path=BorderColor;DataItem=null;目标元素是"SolidColorBrush"(HashCode=8990007);目标属性是"Color"(类型为"Color")
将BorderThickness更改为非均匀值,例如0,1,1,1,将导致边框接收到预期的颜色,并且在调试输出中没有绑定错误。
问题:
为什么BorderBrush的颜色绑定会有这种行为?
这对我来说像是一个真正的错误,请注意边界刷和背景之间的不同行为:
<Border BorderThickness="10">
<Border.BorderBrush>
<SolidColorBrush Color="{Binding BorderColor}" />
</Border.BorderBrush>
<Border.Background>
<SolidColorBrush Color="{Binding BorderColor}" />
</Border.Background>
</Border>
一个明显的解决方法是给窗口一个x:Name("_this"),并通过DataContext显式绑定:
<SolidColorBrush Color="{Binding ElementName=_this, Path=DataContext.BorderColor}" />
遗憾的是,通过RelativeSource绑定似乎也显示了这个问题。