Reputation: 137
I have a DockPanel set up like this
<Window ... >
<DockPanel x:Name="myDock" DataContext="{Binding HonapokList}" >
Inside the Dockpanel there is a TextBox, like this
<TextBox x:Name="tbCount" Text="{Binding Path=Count,Mode=OneWay}" />
</DockPanel>
</Window>
This is how i set up HonapokList, so it's basically a List String>
public List<String> HonapokList;
public MainWindow()
{
InitializeComponent();
HonapokList = new List<string>();
Honapok.ItemsSource = HonapokList;
HonapokList.Add("January");
HonapokList.Add("February");
HonapokList.Add("March");
}
I want my textbox to display the number of elements in the HonapokList ( 3 in this example), however nothing is in it. Why is that?
Upvotes: 2
Views: 1186
Reputation: 81233
First of all you can bind with Properties
only and not with fields
. So, make HonapokList
a property -
public List<String> HonapokList { get; }
Secondly, change your xaml to look up for the property in your Window
class using RelativeSource
-
<DockPanel x:Name="myDock">
<TextBox x:Name="tbCount"
Text="{Binding Path=HonapokList.Count, Mode=OneWay,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=Window}}"/>
</DockPanel>
OR
Set the DataContext
on your window
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}">
and then you can do like this -
<TextBox x:Name="tbCount"
Text="{Binding Path=HonapokList.Count, Mode=OneWay}"/>
Upvotes: 1
Reputation: 24453
Window
doesn't have a default DataContext
, but it looks like you're assuming it to be set to itself. You can set it to do that either in the constructor:
DataContext = this;
or in the XAML:
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}">
You're also going to need to change HonapokList
to be a property, not a field as it is now, in order to bind to it.
Upvotes: 5