118

I have a multi-binding like

<TextBlock>
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource myConverter}">
            <Binding Path="myFirst.Value" />
            <Binding Path="mySecond.Value" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

And I want to pass a fixed value e.g. "123" to one of the two bindings above. How can I do that using XAML?

slugster
  • 49,403
  • 14
  • 95
  • 145
Nam G VU
  • 33,193
  • 69
  • 233
  • 372

4 Answers4

172

If your value is simply a string, you can specify it as a constant in the Source property of a binding. If it is any other primitive data type, you need to define a static resource and reference this.

Define the sys namespace in the root of the XAML to point to System in mscorlib, and the following should work:

<TextBlock>
  <TextBlock.Resources>
    <sys:Int32 x:Key="fixedValue">123</sys:Int32>
  </TextBlock.Resources>
  <TextBlock.Text>
    <MultiBinding Converter="{StaticResource myConverter}">
      <Binding Path="myFirst.Value" />
      <Binding Source="{StaticResource fixedValue}" />
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>
Mitkins
  • 4,031
  • 3
  • 40
  • 77
Noldorin
  • 144,213
  • 56
  • 264
  • 302
122

Or, combining the two answers above:

Define the namespace sys at the document head:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

and then:

<MultiBinding Converter="{StaticResource ScalingConverter}">
    <Binding>
        <Binding.Source>
            <sys:Double>0.5</sys:Double>
        </Binding.Source>
    </Binding>
    <Binding ElementName="TC" Path="ActualWidth" />
</MultiBinding>

Which provides the right type without the Resources kludge.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Anders Kaplan
  • 1,221
  • 1
  • 8
  • 2
  • 6
    It's needed to define the namespace `sys` at the document head: ```xmlns:sys="clr-namespace:System;assembly=mscorlib"``` – Beauty Dec 13 '18 at 12:08
31

I don't quite follow the question but there are two options:

Put the line <Binding Source="123" /> in your multibinding will pass 123 as a bound value to your converter.

Put ConverterParameter="123" in your MultiBinding:

<MultiBinding Converter="{StaticResource conv}" ConverterParameter="123">

benPearce
  • 37,735
  • 14
  • 62
  • 96
  • seems to pass DependencyProperty.UnsetValue – Josh Stribling Jul 10 '15 at 01:25
  • 1
    passes the string "123" instead of the integer or double that I intended in my case. – Marcel Gosselin Jun 11 '18 at 18:49
  • 1
    In `IValueConverter`, the parameters are passed as `object`, which means you would need cast the value to the correct type, in a safe way. [IValueConverter.Convert](https://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.convert(v=vs.100).aspx) – benPearce Jun 14 '18 at 01:32
9

I'm not saying this an especially good answer but here is another approach:

<Binding Path="DoesNotExist" FallbackValue="123" />
David Hollinshead
  • 1,710
  • 17
  • 18