最小,完整,可验证的示例(.NET Framework 4.0 +):
MainWindowViewModel.cs
namespace MCVBorderTest
{
public class MainWindowViewModel
{
public string BorderColor { get { return "Red"; } }
}
}
MainWindow.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>
MainWindow.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>
问题:
运行该应用程序将导致窗口打开,但边框没有颜色。调试输出显示以下消息:
System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。 BindingExpression:Path = BorderColor; DataItem = null;目标元素是'SolidColorBrush'(HashCode = 8990007);目标属性为“颜色”(类型为“颜色”)
将BorderThickness更改为非均匀值(例如0,1,1,1)将导致边框接收其预期的颜色,并且在Debug输出中没有绑定错误。
问题:
BorderBrush的颜色绑定为什么会这样表现?
答案 0 :(得分:1)
在我看来,这似乎是一个真正的错误,请注意边框笔刷和背景之间的不同行为:
<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进行绑定似乎也显示了此问题。