The first time loading a window I want a textbox to be collapsed while keeping a binding to a property (SomeProp) in my Viewmodel.
Unfortunatly I am not able to do this.
what I have tried:
Attempt 1: I have tried to explicity set the value to null in the constructor of the viewmodel and also explicitely call the Onpropertychanged. The Convertor is not triggered.
Attempt 2: In the code behind I've set the default visibility to visibility.Collapsed. this seems to have a side-effect that the Visibility is no longer bound to the SomeProp property.
Attempt 3: After googling I found something about PriorityBinding, but this seems to only work on the TEXT property of the textbox Use a default value when binding cannot be evaluated because of a null value
Thank you in advance,
Extra Info:
I have a textbox and it should only be visible if a property (SomeProp) in my ViewModel has a value 'Other'. I am successfully using a Convertor for this. This means whenever I change the value of SomeProp the textbox becomes visible/invisible depending on the value of SomeProp. I have used the following code: WPF: Binding Visibility by string contents
Does anyone know how I can set te textbox Visibility to Collapsed while keeping the Binding to a property SomeProp.
XAML
<TextBox Name="txtbox" Visibility="{Binding SomeProp.Description, Converter={StaticResource StringOtherToVisibilityConverter}}" TextWrapping="Wrap" Height="150" MaxLength="2000"
Text="{Binding SomeProp2.Text, Mode=TwoWay}"
ScrollViewer.VerticalScrollBarVisibility="Auto" AcceptsReturn="True">
</TextBox>
Convertor
class StringOtherToVisibilityConverter : System.Windows.Markup.MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
if (value.ToString() == "Other")
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null; //DependencyProperty.UnsetValue;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
Setting TargetNullValue={x:Static Visibility.Collapsed}
should collapse the binding target when the source value is null
.
You can also set FallbackValue
, which is applied when the binding or conversion fails. Such failures may include the NullReferenceException
that would occur when binding to X.Y
if X
is null
.