开发者

How to bind to a property of a property in WPF

I have a listview who's itemssource is a ObservableCollection of MyModel. 开发者_StackOverflow社区I am trying to figure how to bind a textbox text's property to the Name property of the model's Owner property

public class Person
{
    public string Name { get; set; }
    public string Address { get; set; }
    //...
}

public class MyModel
{
    public string Title { get; set; }
    public Person Owner { get; set; }
    //...
}

I tried:

<TextBlock Text="{Binding Owner.Name}" /> 

but that leaves the textblock blank. Whats the proper syntax?


The binding looks fine. I assume that you put the TextBlock into a DataTemplate and attached this to the ListView. If yes, that should work.

To find the error, replace the Binding through a literal to see if you have some rows (The literal must be shown in every line). If not, check the ItemsSource. If yes, check that you have really a Person-object attached to your MyModel-instances and that the Name-property is not null or empty. Check also the output window of VS. There you will see binding-errormessages.

If you have no DataTemplate, here an example:

 <ListView ItemsSource="[Your ItemsSource]">
    <ListView.ItemTemplate>                
        <DataTemplate>
            <Grid>
                <TextBlock Text="{Binding Owner.Name}"/>
            </Grid>                    
        </DataTemplate>                
    </ListView.ItemTemplate>                                    
 </ListView>


Check that the DataContext is set properly and implement INotifyPropertyChanged (raise the event it defines when the value of the property changes.).


Try to use Data Source Wizard form VS 2010 I just add these classes and click, clik, clik

<TextBox Grid.Column="1" Grid.Row="0" Height="23" HorizontalAlignment="Left" Margin="3" Name="nameTextBox" Text="{Binding Path=Owner.Name, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true}" VerticalAlignment="Center" Width="120" />


<Slider  Margin="81,161.66,66,0" Name="Height" Minimum="0" Maximum="10" Width="400"></Slider>
<Slider Margin="81,1.66,66,0"  Name="Width" Minimum="0" Maximum="10" Width="400"/>
<Ellipse Height="{Binding ElementName=Height}" Width="{Binding ElementName=Width}"  Fill="Blue" ></Ellipse>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜