Rodhos Soft

備忘録を兼ねた技術的なメモです。Rofhos SoftではiOSアプリ開発を中心としてAndroid, Webサービス等の開発を承っております。まずはご相談下さい。

Converterで値を変える

ボタンをバインディングしているブール値で画像を切り替えたいとする。

    <UserControl.Resources>
        <local:ButtonConverter x:Key="bConverter"/>
    </UserControl.Resources>
                    <Button                         
                        Foreground="{Binding flag,
                                        Converter={StaticResource bConverter}}"
/>

のように、Conveterを通じて変換することになる。Converterの定義は以下のようにする。

    class ButtonConverter : IValueConverter
    {
        object IValueConverter.Convert(object value, Type targetType, object parameter, string language)
        {
            if (value == null) return value;

            bool b = (bool)value;

            String fileURI = this.getUri(b);

            BitmapImage bitmap = new BitmapImage(new Uri(fileURI, UriKind.Absolute));

            ImageBrush brush = new ImageBrush();
            brush.ImageSource = bitmap;
            brush.Stretch = Stretch.Fill;

            return brush;
        }

// 略

    }

パラメータを渡したい時はConverterParameter = "a"などをConveterと並べて追加してやれば良い。