wpf DynamicResource的ResourceKey值进行绑定

wpf 中的DynamicResource 的ResourceKey不支持绑定的,因为它不是个DependencyProperty,但又想动态指定ResourceKey

场景:

Name属性有多个值 zhangsan,lisi,wangwu

对应不同资源文件中的

csharp 复制代码
//  style1
        <sys:String x:Key="zhangsan">张三</sys:String>
        <sys:String x:Key="lisi">李四</sys:String>
        <sys:String x:Key="wangwu">王五</sys:String>
// 另一个文件中的 style2        
		<sys:String x:Key="zhangsan">ZhangSan</sys:String>
        <sys:String x:Key="lisi">LiSi</sys:String>
        <sys:String x:Key="wangwu">WangWu</sys:String>

实现动态改变Name的同时进行动态资源绑定

csharp 复制代码
<ItemsControl ItemsSource="{Binding StudentList}">
            <ItemsControl.ItemTemplate>
                    <HierarchicalDataTemplate>
                    <TextBlock>
                        <TextBlock.Text>
                            <MultiBinding Converter="{StaticResource dynBindingConv}" ConverterParameter="TextProperty">
                                <Binding Path="Name"/>
                                <Binding RelativeSource="{RelativeSource Self}"/>
                            </MultiBinding>
                        </TextBlock.Text>
                    </TextBlock>
                </HierarchicalDataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

可以通过Converter实现,stackoverflow上有个实现方法点击跳转

但工作量太大下面是简陋但能实现效果的方法

xaml:

csharp 复制代码
<converter:DynamicBindingConverter x:Key="dynBindingConv"/>

<TextBlock>
            <TextBlock.Text>
                <MultiBinding Converter="{StaticResource dynBindingConv}" ConverterParameter="TextProperty">
                    <Binding Path="Name"/>
                    <Binding RelativeSource="{RelativeSource Self}"/>
                </MultiBinding>
            </TextBlock.Text>
</TextBlock>
csharp 复制代码
public class DynamicBindingConverter: IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            string key = values[0].ToString();
            var control = values[1] as FrameworkElement;
            string property = parameter.ToString();

            Type type = control.GetType();
            FieldInfo field = type.GetField(property, BindingFlags.Public | BindingFlags.Static);
            DependencyProperty d_property = (DependencyProperty)field.GetValue(null);
            var dynamicResource = new DynamicResourceExtension(key);
            var resourceReferenceExpression = dynamicResource.ProvideValue(null);
            control.SetValue(d_property, resourceReferenceExpression);
            return Application.Current.Resources[key];
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

难点主要是通过反射得到DependencyProperty

发现有的控件找不到对应属性,是因为反射只在当前类中查找不会去父类(或者基类)中查找``对上述代码用下修改即可

csharp 复制代码
public class DynamicBindingConverter: IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            string key = values[0].ToString();
            var control = values[1] as FrameworkElement;
            string property = parameter.ToString();

            Type type = control.GetType();
            FieldInfo field = null;
            while (type != null)
            {
                
                field = type.GetField(property, BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Public);
                if (field != null)
                {
                    break;
                }
                type = type.BaseType;
            }
            if (field != null)
            {
                DependencyProperty d_property = (DependencyProperty)field.GetValue(null);
                var dynamicResource = new DynamicResourceExtension(key);
                var resourceReferenceExpression = dynamicResource.ProvideValue(null);
                control.SetValue(d_property, resourceReferenceExpression);
                return Application.Current.Resources[key];
            }
            else
            {
                return Application.Current.Resources["none"];
            }
            
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
相关推荐
Java Fans14 小时前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf
布伦鸽21 小时前
C# WPF 左右布局实现学习笔记(1)
笔记·学习·c#·wpf
code bean2 天前
【WPF】WPF 项目实战:构建一个可增删、排序的光源类型管理界面(含源码)
wpf
沉到海底去吧Go2 天前
【图片识别改名】如何批量将图片按图片上文字重命名?自动批量识别图片文字并命名,基于图片文字内容改名,WPF和京东ocr识别的解决方案
ocr·wpf·图片识别改名·图片识别重命名·图片内容改名
lph19722 天前
自定义事件wpf
wpf
code bean2 天前
【WPF】从普通 ItemsControl 到支持筛选的 ItemsControl:深入掌握 CollectionViewSource 用法
wpf
碎碎念的安静3 天前
WPF可拖拽ListView
c#·wpf
界面开发小八哥3 天前
界面组件DevExpress WPF中文教程:Grid - 如何识别行和卡片?
.net·wpf·界面控件·devexpress·ui开发
TwilightLemon4 天前
WPF 使用CompositionTarget.Rendering实现平滑流畅滚动的ScrollViewer,支持滚轮、触控板、触摸屏和笔
wpf
Vae_Mars6 天前
WPF中自定义消息弹窗
wpf