我正在尝试在C#中编写一个简单的配置来读取XML并相应地自定义组件(Buttons,Tabs ETC)。我的第一个障碍是从变量调用组件,属性和值。这是一个小的工作片段,但不是我希望它如何工作,因为我没有动态传递组件名称。 (添加到Canvas的虚拟按钮称为btnSample)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication5
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void SetProperty(object target, string propertyName, object value)
{
PropertyInfo property = target.GetType().GetProperty(propertyName);
property.SetValue(target, value, null);
}
private void btnSample_Click(object sender, RoutedEventArgs e)
{
SetProperty(btnSample, "Content", "Clicked");
}
}
}
这不是我想要的100%(上面的工作),这里(下面没有工作)是我已经走了多远而且我被困住了,我正在尝试呼叫名称,属性和价值所有来自变量(源自LINQ / XML),任何帮助都会非常有用:)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication5
{
public partial class Window1 : Window
{
string tar;
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void SetProperty(object target, string propertyName, object value)
{
PropertyInfo property = target.GetType().GetProperty(propertyName);
property.SetValue(target, value, null);
}
private void btnSample_Click(object sender, RoutedEventArgs e)
{
tar = "btnSample";
SetProperty(tar, "Content", "Clicked");
}
}
}
我想我已经解释了什么即可... 感谢您花时间阅读:)
答案 0 :(得分:1)
您正尝试在字符串上设置Content
属性(在本例中为文字"btnSample"
。
我认为你真正想做的就是用这个名字查找按钮。如果您使用x:Name="btnSample"
在XAML中定义它,那么您可以通过该名称查找它,并传递元素本身而不是字符串:
private void btnSample_Click(object sender, RoutedEventArgs e)
{
object element = FindName("btnSample");
SetProperty(element, "Content", "Clicked");
}