例子
直接用一个具体例子来示范吧,比如我的xaml代码如下:
<ItemsControl Name="toSendList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,3,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="4*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding id}" Grid.Column="0" HorizontalAlignment="Center" Margin="2"/>
<TextBox Text="{Binding text}" Grid.Column="1" HorizontalAlignment="Stretch" Margin="0,0,2,0"/>
<Button Content="{Binding commit}" Grid.Column="2" HorizontalAlignment="Stretch" Click="knowSendDataButton_click"/>
<CheckBox IsChecked="{Binding hex}" Grid.Column="3" HorizontalAlignment="Center" Margin="2"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
然后我的绑定代码如下:
ObservableCollection<ToSendData> toSendListItems = new ObservableCollection<ToSendData>();
//这个是主窗口loaded事件,需要在xaml里设置
private void Window_Loaded(object sender, RoutedEventArgs e)
{
toSendList.ItemsSource = toSendListItems;
}
private void knowSendDataButton_click(object sender, RoutedEventArgs e)
{
//我这里面改写些啥呢?
//怎么获取绑定的text数据呢
}
我binding的class结构如下:
public class ToSendData
{
public int id { get; set; }
public string text { get; set; }
public bool hex { get; set; }
public string commit { get; set; }
}
解决
其实解决也很简单,我们给button控件加个Tag
,内容是binding
本身,就能调用了:
<Button Content="{Binding commit}" Tag="{Binding}" Grid.Column="2" HorizontalAlignment="Stretch" Click="knowSendDataButton_click"/>
然后click
事件可以这样获取值了:
private void knowSendDataButton_click(object sender, RoutedEventArgs e)
{
ToSendData data = ((Button)sender).Tag as ToSendData;
//这样就获取了binding的数据了,直接调用data.text就能取出来
}
如果喜欢可以: 点击右侧上方的邮件订阅,订阅本站