Using an IValueConverter in a Binding : IValueConverter « Data « Silverlight






Using an IValueConverter in a Binding

Using an IValueConverter in a Binding
    

<UserControl x:Class='SilverlightApplication3.MainPage'
    xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 
    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
    xmlns:d='http://schemas.microsoft.com/expression/blend/2008' 
    xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006' 
    mc:Ignorable='d' 
    xmlns:my="clr-namespace:SilverlightApplication3"
    d:DesignWidth='640' d:DesignHeight='480'>

    <UserControl.Resources>
        <my:YesNoValueConverter x:Key="myConverter"></my:YesNoValueConverter>
    </UserControl.Resources>

    <StackPanel x:Name="LayoutRoot" Background="White">
        <TextBox x:Name="myTextBox" Text="{Binding IsCorrect, Converter={StaticResource myConverter}}" />
        <Button x:Name="myButton" Content="Bind" Height="30" Width="90" Click="myButton_Click" />
    </StackPanel>
</UserControl>



//File: Page.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication3
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void myButton_Click(object sender, RoutedEventArgs e)
        {
            Test test = new Test(true);
            LayoutRoot.DataContext = test;
        }
    }

    public class YesNoValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType,
            object parameter, System.Globalization.CultureInfo culture)
        {
            bool isYes = Boolean.Parse(value.ToString());
            if (isYes == true)
                return "Yes";
            return "No";
        }

        public object ConvertBack(object value, Type targetType,
            object parameter, System.Globalization.CultureInfo culture)
        {
            string boolText = value.ToString().ToLower();
            if (boolText == "yes")
                return true;
            else if (boolText == "no")
                return false;
            else
                throw new InvalidOperationException("Please enter 'yes' or 'no'.");
        }
    }

    public class Test
    {
        private bool isCorrect = true;
        public bool IsCorrect
        {
            get { return isCorrect; }
        }

        public Test(bool value)
        {
            isCorrect = value;
        }
    }
}

   
    
    
    
  








Related examples in the same category

1.A sample value converter.A sample value converter.
2.Exposing the YesNoValueConverter to XAML