绑定绑定内部

时间:2014-03-06 19:13:56

标签: c# wpf binding listbox

好的我有一个Observable集合,其中包含如此定义的字符串。

public ObservableCollection<string> OCGroundType { get; set; }

这个集合有资源密钥,所以我正在尝试使用此代码

            <ListBox HorizontalAlignment="Left" Height="110" Margin="156,23,0,0" VerticalAlignment="Top" Width="314" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=OCGroundType}" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Label Content="{Binding Path=, Source={StaticResource Resources}}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

所以我要做的是给路径物流源的值是可能的吗?

修改

这就是staticresource被“绑定”的资源,是一个resourceDictionary

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cultures="clr-namespace:Marcam.Cultures"
    xmlns:properties="clr-namespace:Marcam.Properties">

   <ObjectDataProvider x:Key="Resources" ObjectType="{x:Type cultures:CultureResources}" MethodName="GetResourceInstance"/>
</ResourceDictionary>

ObjectType被“绑定”的是一个返回当前Resources.resx的方法,如果我已经很清楚它是如何工作的,因为我已将此代码基于此WPF Localization

2 个答案:

答案 0 :(得分:0)

这是不可能的,因为Binding不是DependencyObject,因此无法绑定其属性。

但是,您可以使用从资源中获取适当值的转换器来实现所需的结果。


编辑:首先,你需要一个像这样的转换器:

public class ResourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string key = (string)value;
        return Properties.Resources.ResourceManager.GetObject(key, culture);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

然后,在XAML资源中声明此转换器的实例:

<local:ResourceConverter x:Key="resourceConverter" />

最后,只需在绑定中使用此转换器:

<Label Content="{Binding Path=., Converter={StaticResource resourceConverter}}"/>

答案 1 :(得分:0)

假设资源仅仅是在Window或UserControl的资源部分下声明的字符串值,您可以使用IMultiValueConverter来实现。

首先您需要在定义资源的任何地方传递{/ 1}}和第二个resource key Window / UserControl。

XAML将如下所示:

ResourceDictionary

当然,您需要在XAML中添加<Label> <Label.Content> <MultiBinding Converter="{StaticResource ResourceToValueConverter}"> <Binding/> <Binding Path="Resources" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=Window}"/> </MultiBinding> </Label.Content> </Label> 的实例。

第二次这里是您的转换器代码:

ResourceToValueConverter

<强>更新

当您编辑问题以包含该资源为public class ResourceToValueConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return ((ResourceDictionary)values[1])[values[0]]; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 时,您可以修改转换器代码。

您的转换器中有ObjectDataProvider,您可以获取并调用它获取资源文件(.resx)文件的方法。从资源文件中获取字符串值并将其返回。

ObjectDataProvider
相关问题