【问题标题】:Access values from xaml file in the code(View) directly直接在代码(视图)中访问 xaml 文件中的值
【发布时间】:2018-07-03 08:25:02
【问题描述】:

我有一个文件 (icons.xaml) 作为文件添加到我的项目的资源中。文件内容如下:

图标.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<VisualBrush x:Key="Bucket"
             Stretch="Uniform">
    <VisualBrush.Visual>
        <Viewbox Stretch="xxxx">
            <Canvas Width="xxxxx"
                    Height="xxxx"> and so on...

Icons.xaml file's properties in vs 2017

现在,我想直接在我的 XAML(视图)代码中使用上述 VisualBrush。行如下:

XAML 代码(视图)

<Setter Property="Icon">
    <Setter.Value>
       <Rectangle Fill="{Binding Bucket, Source={x:Static resx:Resources.Icons}}"/>
    </Setter.Value>
</Setter>

“resx”命名空间定义为:

xmlns:resx="clr-namespace:MyProjectNamespace.Properties"

当我运行我的项目时,我看不到我的图标被绑定到矩形的填充属性,并且我收到了一些 xaml 智能感知错误,即“无法在“字符串”类型的上下文中解析属性“桶”。

目标:我想在我的 View 代码中的 Rectangle 的 Fill 属性中直接在 XAML 中使用 visualbrush 键

注意:我有一个限制,我不能使用下面给出的视图中的代码,我不能在 xaml 代码中使用&lt;ResourceDictionary&gt; 选项卡。

 <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/MyProjectNamespace;component/Resources/Icons.xaml"></ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>
 </ResourceDictionary>

关于我的目标,我是否遵循了正确的方法,还是应该改变这种方法?

我在这个答案中看到了这里使用的方法,但它们都不起作用Get values from *.resx files in XAML

【问题讨论】:

  • icons.xaml 不是 .resx 文件。您需要的是静态资源(或动态资源)&lt;Rectangle Fill="{StaticResource Bucket}"/&gt;。但是您必须先将“图标”资源字典加载到 xaml 代码中视图的 MergedDictionaries 中
  • 好的,首先我需要把它变成一个 resx 文件然后我应该继续吗?因为,我在我的 xaml 文件中使用合并选项卡(或单词)有一个限制
  • 我认为您需要访问 VisualBrush,而不是 .resx 文件。我建议如何从 ResourceDictionary 获取它。 “限制在我的 xaml 文件中使用合并字典选项卡(或单词)” - 不知道这可能意味着什么
  • @ASh 我修改了我的问题
  • 既然你有使用合并字典的限制,你可以使用本地资源吗?

标签: wpf xaml data-binding resourcedictionary


【解决方案1】:

我认为这里的主要问题是 Binding 实际上是在 Resources.Icons 对象上寻找一个名为 Binding 的属性。

试试这个:

<Setter Property="Icon">
    <Setter.Value>
       <Rectangle Fill="{Binding Bucket, Source={x:Static resx:Icons}}"/>
    </Setter.Value>
</Setter>

【讨论】:

  • 如果我在 xaml 中编写您的代码,我会在“图标”一词上收到错误消息,说“无法解析符号 'Icons'”
【解决方案2】:

不需要绑定,试试看:

&lt;Rectangle Fill="{x:Static resx:Resources.Icons.Bucket}"/&gt;

【讨论】:

  • 编译错误“在目标类型上找不到成员“Bucket””。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多