【问题标题】:WPF Binding Via StaticResoucesWPF 通过静态资源绑定
【发布时间】:2011-09-12 07:50:03
【问题描述】:

给定以下 Xaml:

<Window.Resources>
    <System:String x:Key="StringValue"></System:String>
</Window.Resources>
    <Grid>
        <ComboBox Margin="137,101,169,183" ItemsSource="{Binding collection}" SnapsToDevicePixels="True" IsHitTestVisible="true">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                <CheckBox Command="{Binding CheckCommand}" IsChecked="{Binding IsChecked}" Content="{Binding Name}"/>
                    <TextBlock Text="{StaticResource StringValue}" />
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</Grid>

我想要的是将 Textblock Text 绑定到静态资源,即数据绑定到 ViewModel 上的值。问题是 System.String 似乎不允许数据绑定。有人知道这样做的方法吗?对于上下文,TextBlock 需要与其父组合框不同的 itemssource。

谢谢。

【问题讨论】:

  • 您是否包含了 mscorlib 的别名? xmlns:System="clr-namespace:System;assembly=mscorlib" 没有错误出现。
  • 查看我的编辑,寻找可能的包装类,它允许检测字符串的更新

标签: c# wpf xaml binding resources


【解决方案1】:

String 不允许绑定,因为它不是 DependencyObject(并且没有实现 INotifyPropertyChanged)

但是你为什么不直接绑定到 ViewModel 中的值呢?

如果您无法绑定到 ViewModel(考虑使用搜索 Parent 类型的 RelativeSource),您可以实现一个包装器(它实现 INotifyPropertyChanged 以获取对象中的更改)

示例包装类:

public class BindWrapper<T> : INotifyPropertyChanged
{
    private T _Content;
    public T Content
    {
        get
        {
            return _Content; 
        }
        set
        {
            _Content = value;
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs("Content"));
        }
    }


    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

如何在 XAML 中实例化和绑定:

<Window.Resources>
    <local:BindWrapper x:Key="wrapper" x:TypeArguments="System:String">
        <local:BindWrapper.Content>
            <System:String>huuu</System:String>
        </local:BindWrapper.Content>
    </local:BindWrapper>
</Window.Resources>
<TextBlock Text="{Binding Source={StaticResource wrapper}, Path=Content}" />

【讨论】:

  • 我无法直接绑定到该值,因为文本块父级(组合框)在 VM 中有一个可观察集合的 itemsource。它不允许我将 Textblock 与它分开。
  • @Darren Young,是ObservableCollection&lt;string&gt; 还是ObservableCollection&lt;Inline&gt; 还是别的什么?
【解决方案2】:

澄清一下,A System.String 没有依赖属性,所以你不能绑定任何东西。我认为您需要一个转换器,以便您的 TextBlock 可以绑定到视图模型。你在 View Model 上有什么类型的ObservableCollection

EDIT 如果您只想将一个简单的字符串绑定到 text 属性,这是错误的答案。如果您想绑定到格式化文本,请继续阅读。

我之前也遇到过这个问题。我想将我的TextBlock 绑定到我的属性中的字符串资源。我最终将 TextBlock 子类化为 BindableTextBlock 并将 string 的转换器创建为 Inline 列表。

Question and Answers here.

这似乎有点复杂,应该有更简单的方法。但是,每当我需要绑定到某些格式化文本并且它可以工作时,我都会多次重复使用该控件。希望您能从我的工作中受益,也许会有所改进。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多