WPF Binding to specific property
I'm new to DataBinding but would like to accomplish the following:
I have a ViewModel which has a collection of objects: CollectionOfStuff
Each object Stuff has some properties: Name, Value.
In my View, I have a StackPanel with some TextBlocks. I would like to bind the TextBlock's Text property to a specific property. ( I would like to bind to Value when Name of Stuff is "some name" )
On my StackPanel I have set the DataContext to the c开发者_运维技巧ollection.
However for the textblocks, when I try ... Text="{Binding Path=Value"} ... I only get the first object in the CollectionOfStuff. How do I selectively bind to the Value of an object when the Name is "some name" ?
I THINK, from your description, you want to use an ItemsControl, which is backed by a StackPanel by default. It will show all of your items with the given template (I included a very simple one). It would look like this:
<ItemsControl ItemsSource="{Binding CollectionOfStuff}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <TextBlock HorizontalAlignment="Left" Text="{Binding Name}" />
                <TextBlock HorizontalAlignment="Right" Text="{Binding Value}" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
Is that what you want to do? If so, ignore the rest.
If, however, you are looking to bind to a specific item in the list, you will need to make sure that CollectionOfStuff implents a this[string index] indexer (very important step).  Then, you can call it out by name:
<StackPanel DataContext="{Binding CollectionOfStuff['theName']}"></StackPanel>
    <TextBlock HorizontalAlignment="Left" Text="{Binding Name}" />
    <TextBlock HorizontalAlignment="Right" Text="{Binding Value}" />
</StackPanel>
If you are going that route, but you don't have control of the type of collection that CollectionOfStuff is, then you can always create your own indexer on your ViewModel:
public object this[string indexer]
{
    get
    {
        return CollectionOfStuff.FirstOrDefault(s => s.Name == indexer);
    }
}
Then, your DataContext on your StackPanel would look like this: DataContext="{Binding ['theName']}"
I suppose it all depends on what, exactly, you are trying to do. Your solution is in this answer some place :)
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论