开发者

How to bind a property in itemtemplate to a proptery in itemsource?

Consider this container:

public class ItemInfo : DependencyObject
{
    public string Name { get; set; }
    public ObservableCollection<SomeDataItem> DataValues { get; set; }
    ...
    Dependency object registration and event handling
    ...
}

public class MyItemSource : ObservableCollection<ItemInfo>
{
   ...
}

Now, I wish to display this data in a listview where the control that displays the item is custom. For that, I'd set the MyItemSource to listview's ItemSource and define a ItemTemplate. However, it seems that I have no access to ItemInfo in the ItemTemplate. This is my XAML:

    <Grid>
    <ListBox ItemsSource="{StaticResource MyStaticDataSource}" 
         Grid.IsSharedSizeScope="True">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <local:ItemInfoUserControl x:Name="itemInfoUserControl"
       开发者_Go百科         Name = "{Binding Name}"       <--- this doesn't work
                Data = "{Binding DataValues}" <--- this doesn't work
                Width="300" Height="200"  
                Grid.Row="1">
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    </Grid>

Instead of binding to ItemSource's ItemInfo, it binds to the ItemInfoUserControl properties, which is not what I wish it to do. Is there a way to bind properties in itemtemplate to a property in itemsource ? Or is there an alternative approach to what i'm ultimately trying to accomplish ?

Thanks!


Well, first of all you need to use proper binding syntax:

Name = "{Binding Name}"

and

Data = "{Binding DataValues}"

Instead of just "Name = "Binding Name"" and "Data = "Binding DataValues"". Note the addition of "{" and "}" around your binding expression.
This might be enough to solve your problem, as long as Name and DataValues are DependencyProperties in ItemInfoUserControl. If not, you'll need to implement them as DependencyProperties in order to be able to bind to them in XAML. See here for a good MSDN article on defining custom dependency properties.


Edit: Also, just noticed -- you're setting both x:Name and Name. From this article on MSDN:

If Name is available as a property on the class, Name and x:Name can be used interchangeably as attributes, but a parse exception will result if both are specified on the same element. If the XAML is markup compiled, the exception will occur on the markup compile, otherwise it occurs on load.

Remove x:Name="itemInfoUserControl" and see if that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜