更改用户控件的颜色

Cie*_*eja 2 wpf xaml user-controls windows-phone windows-store-apps

可以在我的视图中直接更改用户控件的颜色吗?

<local:MyControl
  // properties
/>
Run Code Online (Sandbox Code Playgroud)

我尝试过使用“Foreground”属性,但它不起作用。

nvi*_*vi9 5

如果控件中的用户控件(例如文本框)内有子控件,则可以将它们的前景属性绑定到控件的前景。例子:

<local:MyControl>
  <TextBox Foreground="{Binding Foreground, RelativeSource={RelativeSource AncestorType={x:Type local:MyControl}}}"/>
  <TextBlock Foreground="the same binding"/>
  ...
</local:MyControl>
Run Code Online (Sandbox Code Playgroud)

如果用户控件未实现任何基类型类(例如FrameworkElementUserControl),则必须创建该Foreground属性,如果您也想使用 WPF 绑定,则还必须创建它的 decency 属性。MyControl.xaml.cs 中的代码:

<local:MyControl>
  <TextBox Foreground="{Binding Foreground, RelativeSource={RelativeSource AncestorType={x:Type local:MyControl}}}"/>
  <TextBlock Foreground="the same binding"/>
  ...
</local:MyControl>
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,您还应该实现INotifyPropertyChanged用于正确更新 WPF 控件的接口。