Value Converters - Access Convert() variables in C

2019-08-23 21:43发布

问题:

I have a converter which has a couple of input variables (an object and a TextBox) and then returns the TextBox.Text String property.

The problem I'm running into is in the ConvertBack() Method of my converter. I have no way of linking any updates back to the object since all I get is a String (the Text of the Textbox). Is there some way I can access some (if not all) the Convert() variables? Or at least know which textbox is calling ConvertBack()?

Here is my ItemsControl Code:

<ItemsControl x:Name="ItemsControlGrid" ItemsSource="{Binding Path=ProjectOrganLocation.LesionTypes, Source={StaticResource Locator}}" >
    <ItemsControl.ItemsPanel>
         <ItemsPanelTemplate>
              <StackPanel Orientation="Horizontal" />
         </ItemsPanelTemplate>
     </ItemsControl.ItemsPanel>
     <ItemsControl.ItemTemplate>
         <DataTemplate>
              <TextBox Width="75" TextAlignment="Center" >
                   <TextBox.Text>
                         <MultiBinding Converter="{StaticResource LesionTypeConverter}"  >
                              <Binding RelativeSource="{RelativeSource AncestorType={x:Type TreeViewItem}}" Path="DataContext.OrganLocation"/>
                              <Binding RelativeSource="{RelativeSource Self}" Path="." />
                          </MultiBinding>
                    </TextBox.Text>
                </TextBox>
            </DataTemplate>
      </ItemsControl.ItemTemplate>
 </ItemsControl>

And here's a snippet from my Converter:

List<CategoryCode> Lesions = organ.getLesionTypes;

    if (organ.OrganDisplayName == organ.CurrentOrgan)
       organ.Count++;
    else
    {
       organ.Count = 0;
       organ.CurrentOrgan = organ.OrganDisplayName;
    }
return organ.Labels[organ.Count].LabelPrefix;

回答1:

Your best bet would be to add a private property to the converter class and store your values during Convert so that ConvertBack can access them. You would need to use a separate instance of the converter for each binding though.

What are you trying to accomplish? There might be a better way to do it than a converter



回答2:

If you assign the bindings in your code behind, you can add a constructor to the converter which takes the sending TextBox (or any other piece of data) as a parameter and record it.