Search code examples
wpfdata-bindingmultibinding

WPF MultiBinding set fallback string for a null binding


If I do not set the Date, the result becomes "price=2000, date=". Can I make it "price=2000, date=unknown" instead?

<TextBlock x:Name="Test">
    <TextBlock.Text>
        <MultiBinding StringFormat="{}price={0}, date={1:d}">
            <Binding Path="Price" />
            <Binding Path="Date" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

public partial class MainWindow : Window
{
    public int Price { get; set; }
    public DateTime? Date { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        Price = 2000;
        //Date = DateTime.Now;
        Test.DataContext = this;
    }
}

Solution

  • In this case, you can use the TargetNullValue Property of your binding:

    <TextBlock x:Name="Test">
        <TextBlock.Resources>
            <local:DateConverter x:Key="DateConverter" />
        </TextBlock.Resources>
            
        <TextBlock.Text>
            <MultiBinding StringFormat="{}price={0}, date={1:d}">
                <Binding Path="Price" />
                <Binding Path="Date" TargetNullValue="unknown" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>