1

IValueConverterの使い方を学ぼうとしています。私は次のコンバーターを持っています:

[ValueConversion(typeof(string), typeof(string))]
public class RequiredFieldConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return "";

        return value.ToString() + "*";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return "";
        var str = value.ToString();
        return str+"Convert Back testing";
    }
}

app.xamlファイルにRequiredFieldConverterリソースを追加しましたが、次のように試してみたいと思います。

<TextBox Name="textBox2"  Width="120" />
<TextBox Text="{Binding ElementName=textBox2, Path=Text, Converter=RequiredFieldConverter}" Name="textBox3" Width="120" />

textbox2に「hello」と入力すると、textbox3に「hello *」と表示されることを期待していましたが、機能しません。実際、実行時に次の例外が発生します。

{"タイプ'System.String'のオブジェクトをタイプ'System.Windows.Data.IValueConverter'にキャストできません。"}

また、値コンバーター関数が機能しているのは、次の場合に機能するためです。

 Content="{Binding Source={StaticResource Cliente}, Converter={StaticResource RequiredFieldConverter}}"
4

1 に答える 1

12

...を参照RequiredFieldConverterとして解釈しようとすると、エラーが発生します。2番目の例で行ったように、またはを使用してコンバーターを参照する必要があります。IValueConverterStaticResourceDynamicResource

<TextBox Text="{Binding ElementName=textBox2, Path=Text, Converter={StaticResouce RequiredFieldConverter}}" Name="textBox3" Width="120" />
于 2012-04-16T23:09:57.360 に答える