我从一个observablecollection构建动态usercontrol
cs代码:
public static ObservableCollection<Model.Model.ControleData> ListControleMachine = new ObservableCollection<Model.Model.ControleData>(); public Genkai(string Autorisation) { InitializeComponent(); DataContext = this; icTodoList.ItemsSource = ListControleMachine; Model.Model.ControleData v = new Model.Model.ControleData(); v.ComputerName = "M57095"; v.ImportSource = "LOAD"; ListControleMachine.Add(v); }
XAML
<ItemsControl x:Name="icTodoList" ItemsSource="{Binding ListControleMachine}" > <ItemsControl.ItemTemplate> <DataTemplate DataType="{x:Type local:ControlMachineII}"> <local:ControlMachineII /> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>
所以在我看来,我有一个类型为“local:ControlMachineII”的用户控件,与Model.Model.ControleData()绑定,但我如何从usercontrole c#代码访问ControleData?
例如,我想删除带有关闭按钮的usercontrole本身,我至少需要访问ControleData.ComputerName值然后从Mainform.ListControleMachine中删除它.
无法找到实现此目的的最佳实践,并在usercontrole代码中使用我的数据.
Genkai.ListControleMachine.Remove(Genkai.ListControleMachine.Where(X => X.ComputerName == "M57095").Single());
解决方法
我看到你今天发布了相同的
question以及更多数据.我将使用该数据提供解决方案.
解决方案1:
使用按钮的Tag属性如下:
<Button Content="Close this UC" HorizontalAlignment="Left" Margin="414,22,0" VerticalAlignment="Top" Width="119" Click="Button_Click" Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}" />
事件处理程序
private void Button_Click(object sender,RoutedEventArgs e) { var button = sender as Button; List<object> list = (button.Tag as ItemsControl).ItemsSource.OfType<TodoItem>().ToList<object>(); list.Remove(button.DataContext); (button.Tag as ItemsControl).ItemsSource = list; }
解决方案2:
更优雅的解决方案
在MainWindow中创建此样式:
<Window.Resources> <Style targettype="Button"> <EventSetter Event="Click" Handler="Button_Click"/> </Style> </Window.Resources>
So Now the Handler of any
Button
Click
event in anyMainWindow's
descendantButton
Control is in theMainWindow.xaml.cs
.
然后将处理程序方法放在MainWindow.xaml.cs中并更改处理程序,如下所示:
private void Button_Click(object sender,RoutedEventArgs e) { var button = sender as Button; items.Remove(button.DataContext as TodoItem); icTodoList.ItemsSource = null; icTodoList.ItemsSource = items; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。