Question

I am trying to get a label bound to two properties to react to a change in the second.

The basis behind this is changing a unit label for a field when switching between metric and imperial:

Image http://s7.postimage.org/wmw3vofmj/test.png

The XAML code is below:

<Label Name="UnitLabel" Grid.Column="1" Foreground="#FF1414AA" HorizontalContentAlignment="Right" VerticalContentAlignment="Center" Padding="2,2,5,2">
    <Label.Content>
        <MultiBinding Converter="{units:UnitConvertor}" Mode="OneWay">
            <Binding Path="Unit" />
            <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=base:MainForm, AncestorLevel=3}" Path="Document.Units" />
        </MultiBinding>
    </Label.Content>
</Label>

The label is hosted on a user control, which the actual document has many of:

Image http://s9.postimage.org/47hvp9uyn/test.png

The Document object is shown below:

public class Document : DependencyObject
{
    public static readonly DependencyProperty UnitsProperty =
        DependencyProperty.Register("Units", typeof (UnitSet), typeof (Document), new PropertyMetadata(default(UnitSet)));

    public UnitSet Units
    {
        get { return (UnitSet) GetValue(UnitsProperty); }
        set { SetValue(UnitsProperty, value); }
    }

    public Document()
    {
        Units = UnitSet.Imperial;
    }
}

I then try and set the Units property:

private void ChangeUnit(object sender, RoutedEventArgs e)
{
    if (sender == Metric)
    {
        Document.Units = UnitSet.Metric;
    }
    else if (sender == Imperial)
    {
        Document.Units = UnitSet.Imperial;
    }
}

However, the unit labels fail to update. What do I need to do to fix this? Apologies if anything obvious has been missed, I started WPF two days ago.

Was it helpful?

Solution

I don't know your full XAML tree, but I think your AncestorLevel is incorrect. I'm guessing MainForm is your root element but you're saying in that binding that you're looking for the 3rd MainForm above that label. Try eliminating the AncestorLevel altogether. It defaults to 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top