Search code examples
wpfmvvmmultibindingvalueconverter

Access Datacontext And A Property In Code Behind At The Same Time


I am using MVVM/WPF and trying to do something seemingly simple, but cant find a clean solution.

I want to do the following:

When a property changes in the model (WPF Textbox text would be changed in this case), use a method to perform other operations on the UI relating to the property bound.

Currently i am using a multibinding on the tooltip (to get the textbox datacontext + binding path), but this is a bit of a hack.

<TextBox x:Name="textBox" Text="{Binding Model.MyProperty}">
 <TextBox.ToolTip>
        <MultiBinding Converter="{StaticResource brNewMultiConverter}">
                <!-- This to trigger the converter in all required cases. 
                     Without it, i cant get the event to fire when filling 
                     the model initially 
                 -->
                <Binding ElementName="textBox" Path="Text" />
                <!-- This has the properties i need, but wont fire without 
                     the binding above -->
                <Binding ElementName="textBox" />
        </MultiBinding>
 </TextBox.ToolTip>
</TextBox>

I would like to make something re-usable and maybe for different controls, hence i am not just using the textchanged event.

If anyone could point me in the right direction, it would be much appreciated.


Solution

  • It looks like you're trying to have the tooltip have the content of the textbox, if so why not just do this?

    <TextBox Text="{Binding Model.MyProperty}" ToolTip="{Binding Model.MyProperty}"/>
    

    If that's not what you want, but want the tooltip to change based on the value of the textbox then do that in your viewmodel e.g.

    public class MyViewModel
    {
      string _MyProperty;
      public string MyProperty
      {
        get { return _MyProperty;}
        set 
        { 
           _MyProperty = value; 
           OnPropertyChanged("MyProperty");
           OnPropertyChanged("MyToolTipProperty"); //force WPF to get the value of MyToolTipProperty
        }
      }
    
      public string MyToolTipProperty
      {
        get 
        { 
          //return what you want
        }
    
      }
    }
    

    and then in your markup:

    <TextBox Text="{Binding Model.MyProperty}" ToolTip="{Binding Model.MyToolTipProperty}"/>