【问题标题】:How to bind to or access color defined in C# class from XAML?如何从 XAML 绑定或访问 C# 类中定义的颜色?
【发布时间】:2011-11-16 18:32:59
【问题描述】:

定义要在 .cs 和 .xaml 文件中使用的对象的正确方法是什么?例如,我在“constants.cs”类中定义了自定义颜色和画笔:

using System.Windows.Media;

namespace MyProject
{
    public static class Constants
    {
        public static Color MyBlue = Color.FromArgb(255, 35, 97, 146);
        public static SolidColorBrush MyBlueBrush = new SolidColorBrush(MyBlue);
    }
}

我想在 .xaml 或 .cs 文件中使用 MyBlue 或 MyBlueBrush。

我可以像这样获得 .cs 文件中的颜色:

namespace MyProject
{
    public partial class MyColorWindow : Window
    {
        public MyColorWindow()
        {
            InitializeComponent();

            btnOne.Background = Constants.MyBlueBrush;
        }
    }
}

但是如何在 XAML 文件中找到它?例如,我应该在下面的代码中添加什么来访问 MyBlueBrush?

<Window x:Class="MyProject.MyColorWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MyColorWindow" Height="300" Width="300">
    <Grid>
    <Button Name="btnOne" Background="Purple" Margin="0,32,0,185" />
    <Button Name="btnTwo" Background="Orange" Margin="0,132,0,85" />  <!-- I want this background to be MyBlueBrush too -->
  </Grid>
</Window>

【问题讨论】:

    标签: c# wpf xaml binding


    【解决方案1】:

    您只能绑定到属性,不能绑定到字段。

    为了从 XAML 绑定,您需要将静态成员转换为属性。

    完成后,您可以通过x:Static Markup Extension 绑定到它们,即:

    <Button Name="btnTwo" 
        Background="{x:Static my:Constants.MyBlueBrush}" 
        Margin="0,132,0,85" />  
    

    (请注意,这也需要“MyProject”命名空间到“my”的 xmlns 映射。)

    【讨论】:

    • 关于类的注释 - 不能嵌套(就像类中的类)。它必须是 class.property 才能工作。没什么大不了的,但是我在尝试为一堆 UI 子类创建包含类时发现编译器抱怨它不能嵌套。
    • @RobbSadler 不是我推荐它,但它可能的:my:Constants+NestedClass.MyBlueBrush 在技术上可以工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    相关资源
    最近更新 更多