views:

37

answers:

1

I have a DatePicker for which I want to set the BorderBrush to SolidColorBrush(Colors.Red) if the SelectedDate is null. If a date has been filled in though, I want to just have the default BorderBrush. I still want to be able to style the default BorderBrush in Blend, so I don't want to hardcode the default borderbrush of the DatePicker. So basically:

xaml:

<controls:DatePicker BorderBrush="{Binding SelectedDate, RelativeSource={RelativeSource Self}, Converter={StaticResource BrushConverter}, Mode=OneWay}"/>

c#:

public class BrushConverter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
            return value == null ?
                new SolidColorBrush(Colors.Red) : /* when value != null have the bound property use it's default value */
        }

is this possible?

A: 

Here is how you can go around the issue:

1) Save DatePicker's BorderBrush at application startup

2) Bind DatePicker's BorderBrush to a public property in the view model (or any type assigned to the Page's DataContext)

3) Implement the DatePicker's SelectedDateChanged event where you assign either the default(saved) brush or red brush to the public property depending on if the DatePicker's SelectedDate is null or not.

In SomePage.xaml:

        <sdk:DatePicker Name="DatePicker"
                    BorderBrush="{Binding DatePickerBorderBrush, Mode=OneWay}"
                    SelectedDateChanged="SelectedDateChanged"
                    Width="120"
                    Height="22"/>

In SomePage.xaml.cs:

public partial class SomePage : UserControl, INotifyPropertyChanged
{
    Brush defaultDatePickerBrush;

    public Brush DatePickerBorderBrush
    {
        get
        {
            return (_DatePickerBorderBrush);
        }
        set
        {
            _DatePickerBorderBrush = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("DatePickerBorderBrush"));
            }
        }
    }
    Brush _DatePickerBorderBrush;

    public MainPage()
    {
        InitializeComponent();
        defaultDatePickerBrush = DatePicker.BorderBrush;
        DatePickerBorderBrush = new SolidColorBrush(Colors.Red);
        DataContext = this;
    }

    private void SelectedDateChanged(object sender, SelectionChangedEventArgs e)
    {
        if (DatePicker.SelectedDate == null)
            DatePickerBorderBrush = new SolidColorBrush(Colors.Red);
        else
            DatePickerBorderBrush = defaultDatePickerBrush;
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
Przemek