在 WPF 开发中会经常用到Binding,而绑定的数据源是变化的,有时候甚至数据源的结构也是变化的,View层设计多种模式,根据数据结构的变化呈现的内容和方式也会不同。下面演示一个小Demo,主要梳理一下动态改变Binding 的思路
public class MyModel
{
public string Label { get; set; }
public string Value { get; set; }
}
<Window x:Class="WpfApp12.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp12"
mc:Ignorable="d"
DataContext="{StaticResource model}"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions >
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock x:Name="tb" Text="{Binding Value}" Foreground="Red" FontSize="22" HorizontalAlignment="Center" VerticalAlignment="Center" />
<StackPanel Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" Orientation="Horizontal">
<StackPanel.Resources>
<Style TargetType="Button">
<Setter Property="Width" Value="100" />
<Setter Property="Height" Value="35" />
<EventSetter Event="Click" Handler="Button_Click" />
</Style>
</StackPanel.Resources>
<Button Tag="btn1" Content="测试1" />
<Button Tag="btn2" Content="测试2" />
</StackPanel>
</Grid>
</Window>
public partial class MainWindow : Window
{
private Binding b1 = new Binding("Label");
private Binding b2 = new Binding("Value");
private MyModel model;
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
model = FindResource("model") as MyModel;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
b1.Source = model;
b2.Source = model;
model.Label = "This Is Label";
model.Value = "My Is Value";
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string str = (sender as Button).Tag as string;
if (str == "btn1") {
tb.SetBinding(TextBlock.TextProperty, b1);
}
else if (str == "btn2")
{
tb.SetBinding(TextBlock.TextProperty, b2);
}
}
}
<Application x:Class="WpfApp12.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp12"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<local:MyModel x:Key="model" Value="值示例" Label="标签示例" />
</ResourceDictionary>
</Application.Resources>
</Application>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!