フォント サイズ スライダーとテキスト ボックスのような 2 つのコントロールをバインドしたいのですが、各コントロールは wpf の別のウィンドウにあるので、どうすればバインドできますか?
6375 次
1 に答える
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
名前のプロジェクトに 2 つの新しい を追加します。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
たWindow
。どちらもビュー モデルのプロパティにバインドされFontSizeSetting
、1 つのウィンドウでプロパティを変更すると、WPF バインディング システムが他の値を自動的に変更します。
于 2013-05-26T14:28:38.197 に答える