2.Xaml绑定选择结果
<StackPanel Orientation="Vertical"> <TextBlock Margin="10,10,10,10" FontWeight="Bold"> Pick a color from below list</TextBlock> <ListBox Name="mcListBox" Height="100" Width="100" Margin="10,10,0,0" HorizontalAlignment="Left" > <ListBoxItem>Orange</ListBoxItem> <ListBoxItem>Green</ListBoxItem> <ListBoxItem>Blue</ListBoxItem> <ListBoxItem>Gray</ListBoxItem> <ListBoxItem>LightGray</ListBoxItem> <ListBoxItem>Red</ListBoxItem> </ListBox> <TextBox Height="23" Name="textBox1" Width="120" Margin="10,10,0,0" HorizontalAlignment="Left" > <TextBox.Text> <Binding ElementName="mcListBox" Path="SelectedItem.Content"/> </TextBox.Text> </TextBox> <Canvas Margin="10,10,0,0" Height="200" Width="200" HorizontalAlignment="Left"> <Canvas.Background> <Binding ElementName="mcListBox" Path="SelectedItem.Content"/> </Canvas.Background> </Canvas> </StackPanel>
3.绑定ListBox.Templete 模板内容
/// <summary> /// List3.xaml 的交互逻辑 /// </summary> public partial class List3 : Window { public List3() { InitializeComponent(); listBox.ItemsSource = new List<UserItem>() { new UserItem(1,"张三",true), new UserItem(2,"李四",false), new UserItem(3,"王五",false), new UserItem(4,"赵六",true) }; } private void Button_MouseDoubleClick(object sender, MouseButtonEventArgs e) { Button btn = sender as Button; if (btn != null) { Image img = btn.FindName("img") as Image; if (img != null) { MessageBox.Show(img.Source.ToString()); } } } } public class UserItem { public UserItem(int ID, string Name, bool IsActive) { this.ID = ID; this.Name = Name; this.IsActive = IsActive; } public int ID { get; set; } public string Name { get; set; } public bool IsActive { get; set; } public string BackGround { get { return this.IsActive ? "/images/1.jpg" : "/images/2.jpg"; } } }
Xaml定义
<Grid> <Grid.RowDefinitions> <RowDefinition Height="33*"/> <RowDefinition Height="236*"/> </Grid.RowDefinitions> <ListBox x:Name="listBox" Grid.Row="1" Margin="30"> <ListBox.ItemTemplate> <DataTemplate> <Button MouseDoubleClick="Button_MouseDoubleClick"> <Grid> <Image x:Name="img" Source="{Binding Path=BackGround}" Width="50" Height="30"></Image> <TextBlock Text="{Binding Path=Name}" Margin="70 10" FontSize="18" Foreground="Red" FontWeight="Bold"></TextBlock> </Grid> </Button> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <Label x:Name="label" Content="List模板绑定" HorizontalAlignment="Left" Margin="21,6,0,0" VerticalAlignment="Top"/> </Grid>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!