【问题标题】:Modify ObjectDataProvider修改 ObjectDataProvider
【发布时间】:2014-08-06 16:38:30
【问题描述】:

我有一个使用 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 类的新实例。

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

提前致谢。

阿尔伯托

【问题讨论】:

  • 你可以尝试设置Application.Current.Resources["odpSettings"] = new AppSettings(); 吗?
  • 您的代码一开始就无法运行,因为Background 的类型为Brush,而绑定属性的类型为Color

标签: c# wpf xaml user-controls objectdataprovider


【解决方案1】:

感谢cmets,我使用了下一个代码:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2010-10-12
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    相关资源
    最近更新 更多