我有一个Silverlight 5项目中的IValueConverter实例,它将自定义数据转换为不同的颜色。我需要从数据库中读取实际的颜色值(因为这些可以由用户编辑)。使用Unity将对象注入到IValueConverter实例中
由于Silverlight使用异步调用通过实体框架从数据库加载数据,因此我创建了一个简单的存储库,该存储库包含来自数据库的值。
接口:
public interface IConfigurationsRepository
{
string this[string key] { get; }
}
实施:
public class ConfigurationRepository : IConfigurationsRepository
{
private readonly TdTerminalService _service = new TdTerminalService();
public ConfigurationRepository()
{
ConfigurationParameters = new Dictionary<string, string>();
_service.LoadConfigurations().Completed += (s, e) =>
{
var loadOperation = (LoadOperation<Configuration>) s;
foreach (Configuration configuration in loadOperation.Entities)
{
ConfigurationParameters[configuration.ParameterKey] = configuration.ParameterValue;
}
};
}
private IDictionary<string, string> ConfigurationParameters { get; set; }
public string this[string key]
{
get
{
return ConfigurationParameters[key];
}
}
}
现在我想用统一注入我的仓库到的IValueConverter实例的这种情况下...
应用.xaml.cs:
private void RegisterTypes()
{
_container = new UnityContainer();
IConfigurationsRepository configurationsRepository = new ConfigurationRepository();
_container.RegisterInstance<IConfigurationsRepository>(configurationsRepository);
}
的IValueConverter:
public class SomeValueToBrushConverter : IValueConverter
{
[Dependency]
private ConfigurationRepository ConfigurationRepository { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
switch ((SomeValue)value)
{
case SomeValue.Occupied:
return new SolidColorBrush(ConfigurationRepository[OccupiedColor]);
default:
throw new ArgumentException();
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
的问题是,我没有在转换器实例(即获得相同的统一容器。存储库未注册)。
如何您的转换器的情况下产生的?你在XAML中设置了它吗? – Jehof 2012-04-23 10:34:00
是的。我将值转换器设置为XAML对象(TextBox的前景)的绑定。 – froeschli 2012-04-23 12:00:43