gpt4 book ai didi

C# 帮助动态改变属性值(反射)

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:48 24 4
gpt4 key购买 nike

我正在尝试用 C# 编写一个简单的配置,它读取 XML 并相应地自定义组件(按钮、选项卡等)。我的第一个障碍是从变量调用组件、属性和值。这是一个小的工作片段,但不是我希望它如何工作,因为我没有动态传递组件名称。 (添加到 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");
}
}
}

我想我已经解释完了,好吧...感谢您花时间阅读 :)

最佳答案

您正尝试在字符串上设置 Content 属性(在本例中为文字 "btnSample"

我认为您真正想要做的是查找具有该名称的按钮。如果您在 XAML 中使用 x:Name="btnSample" 定义它,那么您可以通过该名称查找它,并传递元素本身而不是字符串:

private void btnSample_Click(object sender, RoutedEventArgs e)
{
object element = FindName("btnSample");
SetProperty(element, "Content", "Clicked");
}

有关 FrameworkElement.FindName(string) on MSDN 的更多信息.

关于C# 帮助动态改变属性值(反射),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1477026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com