委托:"System String"无法转换为类型“system . windows . depen

本文关键字:quot 类型 system windows depen System String 委托 转换 | 更新日期: 2023-09-27 18:09:25

我第一次尝试使用委托。因此,我使用了一个带有进度条的例子,它在循环中更新(工作)。之后,我尝试使用相同的代码,但交换了一个应该显示计数器的文本框的进度条。不幸的是,我得到以下错误:

System类型的对象。字符串'无法转换为'System.Windows.DependencyProperty'类型。

有谁知道为什么会出现这个问题,我该如何解决它吗?提前感谢!
    public MainWindow()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Process();
    }
    //Create a Delegate that matches the Signature of the ProgressBar's SetValue method
    private delegate void UpdateSylvacDelegate(System.Windows.DependencyProperty dp, Object value);

    private void Process()
    {
        //Create a new instance of our ProgressBar Delegate that points
        //  to the ProgressBar's SetValue method.
        var updateTextBoxDelegate = new UpdateSylvacDelegate(myTextBox.SetValue);
        double value = 0;
        //Loop
        do
        {
            string value += Convert.ToString(value);
            /*Update the Value of the ProgressBar:
              1)  Pass the "UpdateSylvacDelegate" delegate that points to the myTextBox.SetValue method
              2)  Set the DispatcherPriority to "Background"
              3)  Pass an Object() Array containing the property to update (ProgressBar.ValueProperty) and the new value */
            Dispatcher.Invoke(updateTextBoxDelegate,
                System.Windows.Threading.DispatcherPriority.Background,
                new object[] { TextBox.TextProperty, value });                                
        }
        while (!button2.IsPressed);        
    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
    }

我的XML代码与2个按钮和1个文本框:

<Window x:Class="test2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Prime Numbers" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="210" Width="472">
    <StackPanel Orientation="Horizontal" VerticalAlignment="Center" Name="stackPanel1" Width="363" Height="35">
        <Button Content="START" Height="21" Name="button1" Width="69" Click="button1_Click" />
        <TextBox Height="20" Name="myTextBox" Width="114" />
        <Button Content="STOP" Height="22" Name="button2" Width="63" Click="button2_Click" />
        <ProgressBar Height="23" Name="progressBar1" Width="111" />
    </StackPanel>
</Window>

委托:"System String"无法转换为类型“system . windows . depen

你能不能把UpdateSylvacDelegate的代码给我看看,因为WPF有传递错误的态度。错误发生在updateTextBoxDelegate调用中的某个地方!

还请粘贴包含自定义依赖属性的代码,这些属性可能会受到委托以及文本框所在的xaml的影响!

我将相应地编辑这个答案,希望有解决方案。

我终于找到问题了。虽然看起来很简单,但花了一段时间才看到:)

在"value" (double)和textbox - property(字符串)之间有一个简单的转换问题。

相关文章: