问题
Hello I am trying to give a default value to a textblock if the results returned are null
Here is what I am trying!
All that returns is the String Format I set!
<TextBlock x:Name="NameTxtBlock" Grid.Column="0" Margin="0,0,40,0" FontFamily="Segoe UI" FontSize="14" Text="{Binding Name, StringFormat='Item Name: {0}'}" Padding="2">
<TextBlock.Style>
<Style TargetType="TextBlock" >
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=NameTxtBlock, Path=Text}" Value="{x:Null}">
<Setter Property="FontStyle" Value="Italic"/>
<Setter Property="Text" Value="No Name Found" />
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=NameTxtBlock, Path=Text}" Value="{x:Static System:String.Empty}">
<Setter Property="FontStyle" Value="Italic"/>
<Setter Property="Text" Value="No Name Found" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
回答1:
You could use TargetNullValue Property. This will return TargetNullValue
without StringFormat
if the binding returns Null.
<TextBlock Text="{Binding Name, StringFormat='Item Name: {0}', TargetNullValue='No Name Found'}" />
回答2:
You can use the TargetNullValue
property directly in a binding.
<TextBox Text='{Binding Path=LastName, TargetNullValue="No name found."}' />
回答3:
I would bind the TextBlock to a property of an object that didn't return null; make your property return a default value. It appears that you always want the FontStyle to be Italic, so I would just build that in outside the Triggers.
回答4:
In my applications, I find it more reliable to bind my triggers to the actual object my control is bound to. So, if I am looking at Name in the VM for binding of the actual text, I would bind my data trigger to that as well.
<TextBlock x:Name="NameTxtBlock" Grid.Column="0" Margin="0,0,40,0" FontFamily="Segoe UI" FontSize="14" Text="{Binding Name, StringFormat='Item Name: {0}'}" Padding="2">
<TextBlock.Style>
<Style TargetType="TextBlock" >
<Style.Triggers>
<DataTrigger Binding="{Binding Name}" Value="{x:Null}">
<Setter Property="FontStyle" Value="Italic"/>
<Setter Property="Text" Value="No Name Found" />
</DataTrigger>
<DataTrigger Binding="{Binding Name}" Value="">
<Setter Property="FontStyle" Value="Italic"/>
<Setter Property="Text" Value="No Name Found" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
来源:https://stackoverflow.com/questions/58703730/viewing-a-value-in-a-textbox-and-binding-inputs