I am trying to retrieve Data Binding information from a ComboBox. I try this following Code.
XAML:
<ComboBox Name="ddd" Margin="61,55,273,223" ItemsSource="{Binding myData, ElementName=window}" DisplayMemberPath="name" />
<TextBox Name="te" Height="30" TextChanged="TextBox_TextChanged" Margin="61,140,273,140" Text="{Binding SelectedItem.roll, ElementName=ddd}"/>
<Button Content="Button" Height="50" HorizontalAlignment="Left" Margin="268,120,0,0" Name="button1" VerticalAlignment="Top" Width="151" Click="button1_Click" />
C# Code :
public partial class MainWindow : Window
{
public List<testData> myData { get; set; }
public MainWindow()
{
myData = new List<testData>();
InitializeComponent();
myData.Add(new testData { name = "a", roll = "1" });
myData.Add(new testData { name = "b", roll = "2" });
myData.Add(new testData { name = "c", roll = "3" });
this.DataContext = this;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
var Be = this.ddd.GetBindingExpression(ComboBox.SelectionBoxItemProperty);
var data = (testData)Be.DataItem;
MessageBox.Show(data.roll);
}
}
public class testData
{
public string name { get; set; }
public string roll { get; set; }
}
But it throw "Object reference not set to an instance of an object" exception this line
var data = (testData)Be.DataItem;
where i do wrong ?
thank`s for help.
You are getting that error because you are getting the binding for the SelectionBoxItem
property, which I don't see bound anywhere. So Be
is null
Just use ddd.SelectedItem
to get the selected item, and cast it as a testData
object.
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.