当我尝试使用双向数据绑定更改边框的背景颜色时,我收到以下异常。
{"Must create DependencySource on same Thread as the DependencyObject."}
当我第一次遇到这个错误时,我改变了我的代码,将颜色作为静态资源,希望它可以解决问题,但它没有用。
XAML
<Grid x:Name="BgGrid">
<Grid.Resources>
<Color x:Key="ACGreen">#FF0A7E07</Color>
<Color x:Key="ACYellow">#FFE2BD00</Color>
<Color x:Key="ACRed">#FFAF0B01</Color>
<SolidColorBrush x:Key="GreenBrush" Color="{StaticResource ACGreen}" />
<SolidColorBrush x:Key="YellowBrush" Color="{StaticResource ACYellow}" />
<SolidColorBrush x:Key="RedBrush" Color="{StaticResource ACRed}" />
</Grid.Resources>
<TabControl Style="{StaticResource LeftTabControl}" Background="#FAFAFAFA" HorizontalAlignment="Stretch">
<TabItem x:Name="ConnectionLabelTab" Style="{StaticResource Tab2}" Focusable="False">
<TabItem.HeaderTemplate>
<DataTemplate>
<Border x:Name="ConnectionLabelBorder" Background="{Binding LabelColor, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="70"
DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DataContext}">
<TextBlock x:Name="ConnectionLabelText"
Text="{Binding LabelText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Padding="0,4,0,4"
Foreground="#FAFAFAFA" HorizontalAlignment="Center" VerticalAlignment="Center"
FontSize="10"/>
</Border>
</DataTemplate>
</TabItem.HeaderTemplate>
</TabItem>
</TabControl>
</Grid>
xaml.cs
public partial class TabPanel : UserControl, INotifyPropertyChanged
{
Brush labelcolor;
String labeltext;
public TabPanel()
{
InitializeComponent();
labelcolor = BgGrid.Resources["RedBrush"] as Brush;
labeltext = "Disconnected";
}
public Brush LabelColor
{
get { return labelcolor; }
set
{
labelcolor = value;
PropertyChanged(this, new PropertyChangedEventArgs("LabelColor"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void SetConnected()
{
LabelColor = BgGrid.Resources["GreenBrush"] as Brush;
LabelText = "Connected";
}
}
是否有更好/正确的方法来动态更改背景颜色?如何修复我的代码以停止获取此System.ArguementException?如果我注释掉设置LabelColor,代码工作正常,文本按预期更改。
答案 0 :(得分:3)
我会不确定这是否有效,但您可能需要在调度员上调用。
public void SetConnected()
{
Dispatcher.BeginInvoke(new Action(() => {
LabelColor = BgGrid.Resources["GreenBrush"] as Brush;
LabelText = "Connected";
});
}
原因是,如果从UI线程的某个地方调用SetConnected方法(如计时器或未直接从UI调用的东西),则需要“重新集成”回UI线程以便更新任何UI属性。这在处理WPF绑定时很常见。