wpf binding from a FindAncestor to Dependency Property of custom control

I've got a custom WPF control with a DependencyProperty MyString

I'm using the control within an ItemsControl on my View and want to fish a value out from the ViewModel.

As the DataContext of the control becomes each Item in the ItemsSource of the ItemsControl I thought I'd just be able to use FindAncestor but it dosnt seem to work ... can anyone see where I'm going wrong please?

Heres the XAML on the View ...

<Grid>
    <ItemsControl ItemsSource="{Binding MyItems}" >
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" Name="myStack">
                    <ImportExceptions:ControlStrip MyString="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.MyStringOnViewModel}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>

    </ItemsControl>
</Grid>

and heres the code behind my custom control where I've set up my dependency property ...

public partial class ControlStrip
{

    public ControlStrip()
    {
        InitializeComponent();
    }

    public string MyString
    {
        get
        {
            return GetValue(MyStringProperty).ToString();
        }
        set
        {
            SetValue(MyStringProperty, value);
        }
    }

    public static readonly DependencyProperty MyStringProperty =
        DependencyProperty.RegisterAttached("MyString", typeof (string), typeof (ControlStrip));


}

Your code looks fine. Probably you have made an error in the DataContext reference. In all likeliness the DataContext of the the ItemsControl already is MyStringOnViewModel. So, omit the .MystringOnViewModel after the DataContext in the Path attribute. If not can you give some more code, ore post a simplification of it that mimicks how the DataCon,text(s) is/are set?


The DataContext of the control doesn't change - the DataContext for the ImportExceptions:ControlStrip will be (unless explicitly specified) the next DataContext available as its goes 'up' the visual tree...

I infer from your code that you have set the DataContext of the View to a ViewModel with properties 'MyItems' and 'MyStringOnViewModel' - you should be able to simply bind the MyString property directly to the ViewModel, like

<ImportExceptions:ControlStrip MyString="{Binding Path=MyStringOnViewModel}" />
链接地址: http://www.djcxy.com/p/44604.html

上一篇: 在CustomControl中绑定

下一篇: 从FindAncestor到自定义控件的依赖项属性的wpf绑定