views:

110

answers:

1

I'm using silverlight for windows phone and I want to bind the IsEnabled property of a button to whether a textblock has text in it or not. In other words, I want my button to be enabled when the textblock's Text is not empty and disabled otherwise.

Is it possible to do this purely in XAML using Styles/Setters/Triggers or any other mechanism or do I have to write a converter?

PS: I'm still learning silverlight, .NET etc ..

+3  A: 

As the types are not compatible (and you will generally want to avoid code-behind/dependency properties) a "string to enabled converter" is your best bet for this type of simple check.

As converters are shared around projects, and are only a minor entry in the XAML (and no changes to code-behind) you should not be worried about using converters... converters are your friends :)

Start making a library of useful converters as the same sorts of problems occur time and time again.

Here is some minimal code (no error checks) for a converter that does what you wanted:

using System;
using System.Windows.Data;

namespace LengthToEnabledTest
{
    public class LengthToEnabledConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is string)
            {
                return (value as string).Length > 0;
            }
            throw new NotImplementedException();
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

and some matching test XAML (a simple stack panel with 1 textbox and 1 pushbutton):

<UserControl x:Class="TransitioningContentContolTest.LengthEnabledTest"
    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"
    xmlns:converter="clr-namespace:LengthToEnabledTest"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <converter:LengthToEnabledConverter x:Key="LengthToEnabledConverter"/>
    </UserControl.Resources>
    <StackPanel x:Name="LayoutRoot" Background="White">
        <TextBox x:Name="textBox" />
        <Button Content="Press me" Height="20" IsEnabled="{Binding Text, ElementName=textBox, Converter={StaticResource LengthToEnabledConverter}}"/>
    </StackPanel>
</UserControl>
Enough already