在 WPF 开发中会经常用到Binding,而绑定的数据源是变化的,有时候甚至数据源的结构也是变化的,View层设计多种模式,根据数据结构的变化呈现的内容和方式也会不同。下面演示一个小Demo,主要梳理一下动态改变Binding 的思路
- 模型
public class MyModel
{
public string Label { get; set; }
public string Value { get; set; }
}
- View
<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>
- Code
public partial class MainWindow : Window
{
private Binding b1 = new Binding("Label"); //这里的Binding 对象和Path 路径是固定不变的
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>
标签:绑定,Binding,private,public,WPF,Label,MainWindow,model
From: https://www.cnblogs.com/sundh1981/p/17227230.html