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}}"