簡體   English   中英

C#幫助動態更改屬性值(反射)

[英]C# Help changing property value dynamically (Reflection)

我試圖用C#編寫一個簡單的配置,該配置讀取XML並相應地自定義組件(按鈕,選項卡ETC)。 我的第一個障礙是從變量中調用組件,屬性和值。 這是一個小的工作片段,但不是我希望它如何工作,因為我沒有動態傳遞組件名稱。 (添加到畫布的虛擬按鈕名為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");
}

有關MSDNFrameworkElement.FindName(string)的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM