【问题标题】:How to set a xaml resource value to a constant in code behind如何在后面的代码中将 xaml 资源值设置为常量
【发布时间】:2019-05-24 04:28:17
【问题描述】:

我正在尝试覆盖 WPF 应用程序的垂直滚动条的宽度。将以下代码添加到 App.xaml 引用的资源字典中很有效:

<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">50</sys:Double>

但是,我需要从应用程序的其他地方的代码隐藏中访问该值,因此我想将其设置为代码隐藏常量。

public static class MyConstants
{
    public static double ScrollBarWidth = 50;

但是如何在 xaml 中将此值设置为双精度值? 我已经尝试了所有这些都没有成功:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib"
                    xmlns:constants="clr-namespace:MyProject">

    <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}" Binding="{x:Static constants:MyConstants.ScrollBarWidth}" />
    <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}" Source="{x:Static constants:MyConstants.ScrollBarWidth}" />
    <sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}" Value="{x:Static constants:MyConstants.ScrollBarWidth}" />

【问题讨论】:

  • 绑定只能在属性上完成。 ScrollBarWidth {get; set;} = 50; 但我不确定静态值。也许你应该尝试
  • @NawedNabiZada 我实际上无法将绑定设置为资源句号:The property 'Binding' was not found in type 'Double'。也许我只需要找到魔术关键字来分配它?

标签: .net wpf xaml


【解决方案1】:

您可以将该条目添加到您的资源中,然后在代码中从那里取回它。

        var key = SystemParameters.VerticalScrollBarWidthKey;
        Application.Current.Resources[key] = 42d;
        Double vsbWidth = (Double)Application.Current.Resources[key];
        Console.WriteLine(vsbWidth.ToString());

如果你想覆盖(比如说)窗口范围的值,你可以这样做。资源而不是应用程序。

【讨论】:

  • 太棒了!在我的 app.xaml.cs 中,我只是把它放进去就完成了Current.Resources[SystemParameters.VerticalScrollBarWidthKey] = MyConstants.ScrollBarWidth;
【解决方案2】:

这似乎对我有用

<x:Static x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}" Member="local:Constants.scrollBarWidth" MemberType="{x:Type sys:Double}"></x:Static>

x:Static Markup Extension

【讨论】:

  • 这看起来很有希望,但我收到一个错误'System.Double.constants:MyConstants.ScrollBarWidth' StaticExtension value cannot be resolved to an enumeration, static field, or static property你是如何声明你的常量属性的?
猜你喜欢
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 2022-01-23
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
相关资源
最近更新 更多