c# - 具有统一 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 的颜色绑定会这样?
解决方案
这对我来说看起来像是一个真正的错误,请注意边框画笔和背景之间的不同行为:
<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 绑定似乎也表现出这个问题。
推荐阅读
- docker - 在 Vuex 中使用命名卷
- jupyter-notebook - 虚拟环境中的 Jupyter
- c# - 通过 REST API 返回 HttpClient 的响应
- python - 有没有办法在终端上对多个打印进行单元测试?
- java - 有没有办法在 Springboot 中进行提前编译?
- javascript - 来自谷歌图书 API 的数据在第二次点击事件后显示
- reactjs - 如何在特定页面上不呈现切换按钮?
- tensorflow - 如何在tensorflow中解决“分配具有形状[XXX]的张量时的OOM”(训练GCN时)
- python - TensorFlow 的拟合报告的损失值有什么影响?
- flutter - 如何在颤振中使用if else