无法将String转换为String

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法将String转换为String相关的知识,希望对你有一定的参考价值。

我在xaml中有一个textBox。 但是在导航到其他页面时我收到此消息。 输入,焦点和失去焦点时,动态监视textBox。 (检测是否包含文本并更改文本颜色。) 一切正常,我不知道异常是做什么的。

这是textBox xaml

<TextBox Name="SearchBox" TextChanged="OnTextChanged" Height="72" InputScope="Search" GotFocus="OnGotFocus" KeyDown="OnKeyDown" LostFocus="OnLostFocus"
    Text="{Binding LocalizedResources.Desc_InputKey, Mode=TwoWay, Source={StaticResource LocalizedStrings}}" >
    <TextBox.Foreground>
        <SolidColorBrush x:Name="SearhBoxColor" Color="{StaticResource PhoneTextBoxReadOnlyColor}"/>
    </TextBox.Foreground>
</TextBox>

这是抛出的异常:

System.Windows.Data Error: ConvertBack cannot convert value 'hhh' (type 'System.String'). BindingExpression: Path='LocalizedResources.Desc_InputKey' DataItem='MyProject.LocalizedStrings' (HashCode=15848707); target element is 'System.Windows.Controls.TextBox' (Name='SearchBox'); target property is 'Text' (type 'System.String')..
   System.ArgumentException: Property set method not found.
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
   at System.Windows.CLRPropertyListener.set_Value(Object value)
   at System.Windows.PropertyAccessPathStep.set_Value(Object value)
   at System.Windows.Data.BindingExpression.UpdateValue().

我怎么摆脱它?

答案

您正尝试使用双向绑定绑定本地化资源中的文本。它无法工作,因为这些资源是只读的。

我相信你只是想设置文本框的初始值。因此,您应该绑定到您自己的属性,并使用资源对其进行初始化。

首先,在viewmodel中创建属性:

public string SearchBoxColorText { get; set; }

在代码的某处初始化属性(在类构造函数中,在OnNavigatedTo事件中,适合您的工作流程):

this.SearchBoxColorText = LocalizedStrings.StaticlocalizedResources.Desc_InputKey;

然后将文本框绑定到此属性:

<TextBox Name="SearchBox" Text="{Binding SearchBoxColorText}" >

以上是关于无法将String转换为String的主要内容,如果未能解决你的问题,请参考以下文章

无法将对象类型“System.String[*]”转换为“System.String[]”

为啥在片段中从 char* 转换为 std::string 比转换为 const char* 更可取?

无法将类型“string”隐式转换为“System.Threading.Tasks.Task<string>”

C#错误(无法将类型'string'隐式转换为'int')[重复]

无法将String强制转换为List

Swift 4.1 - 无法将 [Character] 类型的值转换为 [String]