【问题标题】:Windows Runtime dependency properties that depend on each other相互依赖的 Windows 运行时依赖项属性
【发布时间】:2020-08-31 10:31:27
【问题描述】:

我有一个用 C++/CX 编写的 Windows 运行时组件,它包含四个依赖项属性。其中三个属性在底层渲染器中将颜色通道设置为红色、绿色和蓝色。此类属性的 C++/C 代码如下所示:

uint8_t DemoControl::Red::get()
{
  return static_cast<uint8_t>(GetValue(RedProperty));
}

void DemoControl::Red::set(uint8_t r)
{
  SetValue(RedProperty, r);
}

DependencyProperty^ DemoControl::_redProperty =
  DependencyProperty::Register("Red",
                               uint_t::typeid,
                               DemoControl::typeid,
                               ref new PropertyMetadata(127, ref new PropertyChangedCallback(&DemoControl::OnRedChanged)));

void DemoControl::OnRedChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
{
  DemoControl^ DemoControl = static_cast<DemoControl^>(d);
  DemoControl->renderer->SetRed(static_cast<uint8_t>(e->NewValue));
}

第四个属性返回整个颜色,即它是其他三个属性值的组合。

问题是,如果红色、绿色或蓝色属性发生变化而不触发通过数据绑定附加到颜色属性的代码,我将如何更新该颜色属性?

here 提出了类似的问题,但针对 WPF。答案建议使用value coercion,但这似乎是 Windows 运行时组件不可用的功能。注册依赖属性时使用的PropertyMetadata对象不支持CoerceValueCallback,据我所知。

【问题讨论】:

    标签: windows-runtime dependency-properties c++-cx


    【解决方案1】:

    我不是 C++ 专家,但至少对于您的情况,我想我可以提供帮助。

    您可以为多个依赖属性注册相同的回调。因此,在您的具体情况下,您可能只需要一个 OnColorComponentChanged 回调:

    void DemoControl::OnColorComponentChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
    {
      DemoControl^ DemoControl = static_cast<DemoControl^>(d);
    
      if (e->Property == DemoControl::RedProperty) // Hand Wave Syntax Here
      {
        DemoControl->renderer->SetRed(static_cast<uint8_t>(e->NewValue));
      }
      else if (e->Property == DemoControl::GreenProperty)
      {
        DemoControl->renderer->SetGreen(static_cast<uint8_t>(e->NewValue));  
      }
      else if (e->Property == DemoControl::BlueProperty)
      {
        DemoControl->renderer->SetBlue(static_cast<uint8_t>(e->NewValue));  
      }
    
      // Hand Wave Here
      DemoControl->Color = MakeColor(DemoControl->Red, DemoControl->Green, DemoControl->Blue);
    }
    

    【讨论】:

    • 感谢您的意见,非常感谢。您的方法适用于代表各个颜色通道的三个属性,即它们可以共享相同的回调。但是,组合颜色属性的回调需要更新各个颜色通道属性。为了防止它们永远相互更新的无限循环,我拆分了回调并使用布尔值来防止调用连续的回调。我把这个问题留了一会儿。也许有人想出了我不知道的 Windows 运行时机制。如果不是,我将发布我的解决方案。
    • 是的,反过来看守布尔值是有意义的。虽然它不会直接帮助您,但请随时在Windows Community Toolkit 上提出建议。我认为,如果我们能在未来针对这些类型的场景集思广益,那就太好了。
    猜你喜欢
    • 2013-07-19
    • 2016-04-13
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2011-09-18
    • 1970-01-01
    相关资源
    最近更新 更多