嵌套用户控件中的WPF订购数据绑定

时间:2019-01-30 01:27:35

标签: c# wpf data-binding wpf-controls

我有两个用户控件:“ Flags”和“ FlagOption”。像这样,“ FlagOption”嵌套在“ Flags”控件的ItemsControl中:

标记控制:

<ItemsControl ItemsSource="Binding RelativeSource={RelativeSource AncestorType=local:Flags}, Path=FlagOptions}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <local:FlagOption FlagValue="{Binding}" Field="{Binding RelativeSource={RelativeSource AncestorType=local:Flags}, Path=Field}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

CodeBehind:

public static readonly DependencyProperty FieldProperty = DependencyProperty.Register(nameof(Field), typeof(TagInterface.LongFlags), typeof(Flags));

public TagInterface.LongFlags Field
{
    get { return (TagInterface.LongFlags)GetValue(FieldProperty); }
    set { SetValue(FieldProperty, value); }
}

public IEnumerable<Enum> FlagOptions
{
    get
    {
        return Enum.GetValues(Field.FieldValue.GetType()).Cast<Enum>();
    }
}

FlagOption控件:

<CheckBox FlowDirection="LeftToRight" IsChecked="{Binding Path=IsChecked, RelativeSource={RelativeSource AncestorType=local:FlagOption}}"/>

CodeBehind:

public static readonly DependencyProperty FlagValueProperty = DependencyProperty.Register(nameof(FlagValue), typeof(Enum), typeof(FlagOption));
public static readonly DependencyProperty FieldProperty = DependencyProperty.Register(nameof(Field), typeof(TagInterface.LongFlags), typeof(FlagOption));

public Enum FlagValue
{
    get { return (Enum)GetValue(FlagValueProperty); }
    set { SetValue(FlagValueProperty, value); }
}

public TagInterface.LongFlags Field
{
    get { return (TagInterface.LongFlags)GetValue(FieldProperty); }
    set { SetValue(FieldProperty, value); }
}

public bool IsChecked
{
    get
    {
        // Accessing Field Property here is null because it is bound AFTER IsChecked field
        return false;
    }
    set
    {
        // TODO
    }
}

我遇到的问题是,在FlagCheck控件中,“字段”依赖项属性在IsChecked属性之后被绑定,因此在IsChecked属性的Getter中,Field属性为null。如果调试并越过该错误,则最终会绑定“ Field”依赖项属性,但为时已晚。

我可以以某种方式控制绑定的顺序吗?为什么在我的IsChecked属性之前不绑定字段依赖属性?

0 个答案:

没有答案