سؤال

I have a WPF TextBox with the Text property bound to a data source. I am also binding the IsEnabled property of a second TextBox to the Text.Length property of the first in order to disable the second box when there is nothing entered in the first box. The problem is I want the text source to update on property changed but the IsEnabled to only update on lost focus but I can only define one UpdateSourceTrigger for the text properly.

One way around this would be to manually enable and disable the textboxes on the lost focus event of the previous text boxes. However since there are a lot of these text boxes each with its IsEnabled bound to the previous box's Text property this would be messy. I was wondering if there was a cleaner way of doing this in the Xaml.

<TextBox Name="box1" Text="{Binding textSource1, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<TextBox Name="box2" IsEnabled="{Binding ElementName=box1, Path=Text.Length}" Text="{Binding textSource2, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>

Here I want the IsEnabled property of box2 to update when box1 loses focus but textSource1 to update when the Text property on box1 changes.

هل كانت مفيدة؟

المحلول

You could use a MultiBinding class.

<TextBox Name="box2"  Text="{Binding textSource2, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Margin="321,64,113,217">
        <TextBox.IsEnabled>
            <MultiBinding  Converter="{StaticResource myConv}">
                <Binding ElementName="box1" Path="Text.Length" />
                <Binding ElementName="box1" Path="IsFocused" />
            </MultiBinding>
        </TextBox.IsEnabled>
</TextBox> 

Then you need a converter class with the desired custom logic

public class MyConverter : IMultiValueConverter
{

    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int textLength = (int)values[0];
        bool isFocused = (bool)values[1];

        if (textLength > 0)
            return true;

        if (isFocused == true)
            return true;

        return false;
    }

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

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top