0

我有一个使用 ObjectDataProvider (App.xaml) 的应用程序:

<Application x:Class="Example.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:src="clr-namespace:Example.Settings"
         StartupUri="MainWindow.xaml"
         Startup="Application_Startup"
         DispatcherUnhandledException="ApplicationDispatcherUnhandledException">
<Application.Resources>
    <ObjectDataProvider x:Key="odpSettings" ObjectType="{x:Type src:AppSettings}"/>
</Application.Resources>

我的课是:

class AppSettings : INotifyPropertyChanged
{
    public AppSettings()
    {

    }

    Color itemColor = Colors.Crimson;

public Color ItemColor
    {
        get
        {
            return itemColor;
        }
        set
        {
            if (itemColor == value)
                return;

            itemColor = value;

            this.OnPropertyChanged("ItemColor");
        }
    }

public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }   

}

然后我有一个使用该颜色的用户控件,例如:

<Border Background="{Binding Source={StaticResource odpSettings}, 
                             Path=ItemColor,Mode=TwoWay}" />

我将该 UserControl 添加到我的 MainWindow 中,其中我有一个 ColorPicker 控件,我想修改我的 UserControl 的边框背景颜色,并选择了 ColorPicker 颜色。

我试过这样的事情:

AppSettings objSettings = new AppSettings();
objSettings.ItemColor = colorPicker.SelectedColor;

当我使用 ColorPicker 更改颜色时,我的 UserControl 中的颜色没有改变,我想这是因为我正在创建 AppSettings 类的新实例。

有没有办法完成我想做的事情?

提前致谢。

阿尔贝托

4

1 回答 1

0

感谢您的评论,我使用了下一个代码:

AppSettings objSettings = (AppSettings)((ObjectDataProvider)Application.Current.FindResource("odpSettings")).ObjectInstance;

这样我就可以访问和修改属性 ItemColor 的值。

我还将属性类型更改为 SolidColorBrush。

objSettings.ItemColor = new SolidColorBrush(colorPicker.SelectedColor);
于 2014-08-07T23:18:58.493 回答