2015-07-10 39 views
0

當我嘗試使用雙向數據綁定更改邊框的背景顏色時,出現以下異常。WPF在嘗試使用雙向綁定設置背景時拋出System.ArgumentException

{"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

這是發生在SetConnected方法?如果是的話,那是從哪裏來的? – kmacdonald

+0

你知道線程是什麼嗎?我不想聽起來光​​顧,但你試圖解決的問題意味着你不理解異常信息。 – phoog

回答

3

我不知道這是否會工作,但你可能需要在調度器上調用。

public void SetConnected() 
{ 
    Dispatcher.BeginInvoke(new Action(() => { 
     LabelColor = BgGrid.Resources["GreenBrush"] as Brush; 
     LabelText = "Connected"; 
    }); 
} 

其原因是,如果SetConnected方法是從什麼地方取消了UI線程的(如定時器或東西不是直接從用戶界面調用),它需要「重返」回UI線程以更新任何UI屬性。處理WPF綁定時,這是很常見的事情。