Примените стиль к текстовому блоку Windows Phone, если он не содержит текста - PullRequest
2 голосов
/ 10 января 2012

Я пытаюсь найти способ применить стиль к элементу TextBox, когда он не содержит текста.Я хочу, чтобы TextBox имел другой цвет фона (например), когда он содержит или не содержит текст.

Поскольку триггеры - это не то, что я могу использовать в Silverlight (afaik), есть ли другой способсделай это?Желательно без написания пользовательской реализации TextBox только для этого поведения.Спасибо.


В итоге я использовал поведение по умолчанию (ConditionBehavior):

<i:Interaction.Triggers>
    <i:EventTrigger EventName="TextChanged">
        <i:Interaction.Behaviors>
            <ec:ConditionBehavior>
                <ec:ConditionalExpression>
                    <ec:ComparisonCondition LeftOperand="{Binding Text, ElementName=textBox}" RightOperand="" Operator="NotEqual"/>
                </ec:ConditionalExpression>
            </ec:ConditionBehavior>
        </i:Interaction.Behaviors>
        <ec:ChangePropertyAction PropertyName="Background" Value="{StaticResource PhoneTextBoxBrush}" />
    </i:EventTrigger>
    <i:EventTrigger EventName="TextChanged">
        <i:Interaction.Behaviors>
            <ec:ConditionBehavior>
                <ec:ConditionalExpression>
                    <ec:ComparisonCondition LeftOperand="{Binding Text, ElementName=textBox}" RightOperand="" Operator="Equal"/>
                </ec:ConditionalExpression>
            </ec:ConditionBehavior>
        </i:Interaction.Behaviors>
        <ec:ChangePropertyAction PropertyName="Background" Value="Transparent" />
    </i:EventTrigger>
</i:Interaction.Triggers>

Ответы [ 2 ]

1 голос
/ 11 января 2012

Создание ваших стилей

  <Style x:Key="FilledStyle" TargetType="TextBox">
            <Setter Property="Background" Value="Beige" />
        </Style>

        <Style x:Key="EmptyStyle" TargetType="TextBox">
            <Setter Property="Background" Value="Yellow" />
        </Style>


 <Models:TextStyleConverter x:Key="TextStyleConverter" />

Создание конвертера

public class TextStyleConverter : IValueConverter
    {
    #region Implementation of IValueConverter

    /// <summary>
    /// Modifies the source data before passing it to the target for display in the UI.
    /// </summary>
    /// <returns>
    /// The value to be passed to the target dependency property.
    /// </returns>
    /// <param name="value">The source data being passed to the target.</param><param name="targetType">The <see cref="T:System.Type"/> of data expected by the target dependency property.</param><param name="parameter">An optional parameter to be used in the converter logic.</param><param name="culture">The culture of the conversion.</param>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var val = value as string;
        if (String.IsNullOrEmpty(val)) return Application.Current.Resources["EmptyStyle"];

        return Application.Current.Resources["FilledStyle"];
    }

    /// <summary>
    /// Modifies the target data before passing it to the source object.  This method is called only in <see cref="F:System.Windows.Data.BindingMode.TwoWay"/> bindings.
    /// </summary>
    /// <returns>
    /// The value to be passed to the source object.
    /// </returns>
    /// <param name="value">The target data being passed to the source.</param><param name="targetType">The <see cref="T:System.Type"/> of data expected by the source object.</param><param name="parameter">An optional parameter to be used in the converter logic.</param><param name="culture">The culture of the conversion.</param>
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

Использование

 <TextBox x:Name="locationtbx" Style="{Binding ElementName=locationtbx, Path=Text, Converter={StaticResource TextStyleConverter}}"  />
1 голос
/ 11 января 2012

Это должно быть довольно легко сделать с помощью пользовательского поведения. Используйте эту ссылку , чтобы создать поведение, которое можно прикрепить к элементу управления TextBox. В методе OnAttached вы можете обработать событие TextChanged даже метода LostFocus, чтобы проверить, является ли TextBox пустым или нет. Соответственно, вы можете переключать стиль между стилями.

P.S .: Вам может нужно вызвать метод TextBox.ApplyTemplate () после изменения стиля. Обратите внимание, конечно, об этом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...