简体   繁体   中英

Can an item in an ItemsControl be the target of a binding?

In the code below I want the second item to be bound to a property on my viewmodel. How do I accomplish that? I don't want to create a list or ObservableCollection in code.

<ItemsControl>
    <ItemsControl.Items>
        <local:InfoTableItem Data="Hi there!"/>
        <local:InfoTableItem Data="{Binding MyProperty}"/>
    </ItemsControl.Items>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Data}"/>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>




public class InfoTableItem : DependencyObject
{

    public string Data
    {
        get { return (string)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(string), typeof(InfoTableItem), new PropertyMetadata(String.Empty));

}

This question is a more concise statement of the question asked here:

How do I write this ItemsControl so WPF will use bindings to generate columns for the output grid

See the above for the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM