我想绑定两个控件,如字体大小滑块和文本框,每个控件都在wpf的不同窗口,所以如何绑定它们?
答案 0 :(得分:4)
以下是如何操作的示例:
1)创建一个WPF项目。
2)将MainWindow.xaml
的内容更改为以下内容(不要忘记更正我发布的所有代码中的命名空间,例如在我的代码中,命名空间是WpfApplication2
):
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Button Content="Settings Window" Click="SettingsWindowButton_OnClick"/>
<Button Content="Bound Window" Click="BoundWindowButton_OnClick"/>
</StackPanel>
</Window>
3)将MainWindow.xaml.cs
的内容更改为以下内容:
namespace WpfApplication2
{
using System.Windows;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
ViewModel viewModel = new ViewModel();
public MainWindow()
{
InitializeComponent();
}
private void SettingsWindowButton_OnClick(object sender, RoutedEventArgs e)
{
var settingsWindow = new SettingsWindow();
settingsWindow.DataContext = viewModel;
settingsWindow.Show();
}
private void BoundWindowButton_OnClick(object sender, RoutedEventArgs e)
{
var boundWindow = new BoundWindow();
boundWindow.DataContext = viewModel;
boundWindow.Show();
}
}
}
4)使用以下代码在项目中创建名为ViewModel
的类:
namespace WpfApplication2
{
using System.ComponentModel;
public class ViewModel : INotifyPropertyChanged
{
private int _fontSizeSetting = 10;
public event PropertyChangedEventHandler PropertyChanged;
public int FontSizeSetting
{
get { return _fontSizeSetting; }
set
{
_fontSizeSetting = value;
OnPropertyChanged("FontSizeSetting");
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
5)使用以下标记向名为Window
和BoundWindow
的项目添加两个新的SettingsWindow
:
<Window x:Class="WpfApplication2.BoundWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BoundWindow" Height="300" Width="300">
<Grid>
<TextBox FontSize="{Binding FontSizeSetting, Mode=TwoWay}" Text="test..."/>
</Grid>
</Window>
-
<Window x:Class="WpfApplication2.SettingsWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="SettingsWindow" Height="300" Width="300">
<Grid>
<Slider Value="{Binding FontSizeSetting, Mode=TwoWay}" Minimum="10" Maximum="100"/>
</Grid>
</Window>
现在一切都应该按预期工作了。您基本上做的是创建一个视图模型,将其设置为DataContext
的{{1}}。它们都绑定到视图模型的Window
属性,当您在一个窗口中更改它时,WPF绑定系统会自动更改其他值。