kr13
kr13

Reputation: 537

Implementing IValueConverter to get Name from ID

I have a table column called LOCATION_ID. I want to show the LOCATION_NAME which is located in the LOCATION table instead of the ID.

I am trying to implement IValueConverter but can't figure out how to do it. I am using WPF with entity framework.

How would I pass the ID value to this converter?

I have a method name GetLocationNameByID(). Where in the converter would I Call this method? And how would I bind the return value to the datagrid XAML?

Upvotes: 0

Views: 576

Answers (2)

Tony Vitabile
Tony Vitabile

Reputation: 8594

Implementing the IValueConverer interface is pretty straightforward. In the XAML, you'd have something like this:

<Window x:Class="CarSystem.CustomControls.AlarmDisplayer"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyNameSpace"
        DataContext="{Binding Path=MyDataContextObject, RelativeSource={RelativeSource Self}">

<Window.Resources>
    <local:MyIValueConverter x:Key="Converter" />
</Window.Resoures>

<TextBox Text="{Binding Converter={StaticResource Converter} Path=MyProperty}" />

</Window>

When WPF detects a change in the value of the MyProperty in the MyDataContextObject, it calls the MyIValueConverter object's Convert method, passing the value of the property as the Value parameter. Your implementation of the Convert method does what it has to do & returns the string to be displayed.

Upvotes: 3

swcraft
swcraft

Reputation: 2112

you can use multi-binding, have your value converter implement the IMultiValueConverter interface. The converter takes an object array, each of which can be a binding to your XAML.

<TextBox>  
   <TextBox.Text>  
      <MultiBinding Converter="{StaticResource MyConverter}">  
          <MultiBinding.Bindings>  
             <Binding Path="SomeProperty" />  
             <Binding RelativeSource="{RelativeSource Self}"/>  
          </MultiBinding.Bindings>  
       </MultiBinding>  
   </TextBox.Text>  
</TextBox>  

Upvotes: 0

Related Questions