在WPF中的两个窗口之间共享相同的对象

时间:2013-09-27 17:12:31

标签: c# wpf

我的班级代表我的AppSettings 我有Main窗口和Settings窗口。

每个窗口都包含对象AppSettings

的实例

所以这两个对象是不同的。 如果AppSettings窗口中的对象Settings发生更改,则更改未反映在AppSettings窗口的Main中。

我有什么方法可以在Windows之间共享AppSettings对象,所以我只有一个实例?

我尝试创建共享基类但出现错误

Partial declarations of "class name" must not specify different base classes    

5 个答案:

答案 0 :(得分:2)

您可以在一个类中创建静态属性,并在其他类的静态属性上创建包装器属性。

此外,如果您将此属性绑定到UI,那么您不需要两个属性..您可以绑定到静态实例。

答案 1 :(得分:1)

  

有没有办法可以在Windows之间共享AppSettings对象,所以我只有一个实例?

你需要一些方法让两个窗口获得相同的引用。如果将对同一AppSettings对象的引用传递给两个Windows,则应该可以正常工作。

答案 2 :(得分:1)

我知道这个答案可以解决这个话题,但我找到了其他更简单的方式来做所谓的事情,以便将来可以帮助任何人。 在每个WPF应用程序中都创建了app.xaml和app.xaml.cs。 因此,在app.xaml.cs中创建一个设置对象,它看起来像这样:

$(function() {
	$("#form").on("submit", function(event) {
		event.preventDefault();
		 
		$.ajax({
			url: "check_data.php",
			type: "POST",
			data: $(this).serialize(),
			success: function(d) {
				alert(d);
			}
		});
	});
});

现在要从不同的窗口引用此对象,您可以使用: namespace WpfApplication { public partial class App : Application { // Settings : public int setting_1 { get; set; } //some setting variable public string setting_2 { get; set; } //some other setting variable } }

答案 3 :(得分:0)

您可以在项目中使用“Utils”这样的类,其属性如下:

Public Shared(or Static in C#) AppSettings  As YourObjectType

然后在Windows的xaml中使用Utils.AppSetings以两种方式进行模式绑定

答案 4 :(得分:0)

当然有。您可以在两个窗口AppSettings中创建DependencyProprerties属性,然后在创建Settings窗口时将Main中的属性绑定到Settings窗口的属性。也就是说,在SettingsWindow类中:

partial class SettingsWindow : Window {

    public static readonly DependencyProperty AppSettingsProperty("AppSettings", typeof(AppSettings), typeof(SettingsWindow), new PropertyMetaData(null));

    public AppSettings AppSettings {
        get { return (AppSettings) GetValue(AppSettingsProperty); }
        set { SetValue(AppSettingsProperty, value); }
    }

}

然后,在Main窗口类的代码后面:

partial class MainWindow : Window {

    public static readonly DependencyProperty AppSettingsProperty("AppSettings", typeof(AppSettings), typeof(MainWindow), new PropertyMetaData(null));

    public AppSettings AppSettings {
        get { return (AppSettings) GetValue(AppSettingsProperty); }
        set { SetValue(AppSettingsProperty, value); }
    }

    private void ShowSettingsWindowButton_Click(object sender, RoutedEventArgs e ) {
        SettingsWindow settingsWindow = new SettingsWindow();
        Binding appSettingsBinding = new Binding("AppSettings");
        appSettingsBinding.Source = this;
        appSettingsBinding.Path = new PropertyPath( "AppSettings" );
        appSettingsBinding.Mode = BindingMode.TwoWay;
        BindingOperations.SetBinding( this, AppSettingsProperty, appSettingsBinding );
        settingsWindow.ShowDialog();
    }
}

Binding机制将使两个对象中的属性保持同步。因此,如果在SettingsWindow打开时将一个类中的属性值替换为另一个实例,则会SettingsWindows通知更改并更新其副本。