2015-05-02 38 views
1

我試圖讓TextBlock中的文本與ListBox項目中的文本更新,當我左鍵單擊該項目時。C#WPF ListBox鼠標點擊已晚

我的C#代碼:

private void listBox_MouseDown_rem(object sender, MouseButtonEventArgs e) 
{ 
    if (pathListB.SelectedItem != null) 
    { 
     rem_block.Text = pathListB.SelectedValue.ToString(); 
    } 
} 

XAML:

<ListBox Name="pathListB" PreviewMouseLeftButtonDown="listBox_MouseDown_rem" HorizontalAlignment="Left" Height="246" Margin="10,10,0,0" VerticalAlignment="Top" Width="491"/> 
<TextBlock Name="rem_block" HorizontalAlignment="Left" Margin="10,261,0,0" TextWrapping="Wrap" Text="Select Item to Remove" VerticalAlignment="Top" Height="20" Width="411"/> 

現在,所有的這做什麼它應該,除了當我選擇ListBoxItem(我有一個循環的其他地方填充此ListBox )它只會在我下一次點擊鼠標時更新到我以前的值,所以它總是「遲到」。

因此,例如,我的列表框具有以下項目:

Sentence 1 
Sentence 2 
Sentence 3 

我會點擊「句子1」,和我的TextBlock不會改變。我點擊「句子3」,TextBlock更新爲「句子1」等。它總是更新爲先前的值。

+0

PreviewMouseLeftButtonDown發生在select之前。使用鼠標按下事件。 – Paparazzi

回答

0

在PreviewMouseDown上,ListBox項目尚未更改。相反,使用PreviewMouseUp事件會在項目已更改時觸發。

+0

這個伎倆。非常簡單的修復,謝謝。 – morningreis

0

您可以創建一個名爲SelectedItem的屬性(您綁定的集合是什麼類型)並將其綁定到ListBox的SelectedItem屬性。然後將TextBlock的Text屬性綁定到您定義的SelectedItem屬性。

創建SelectedItem屬性:

public string SelectedItem 
    { 
     get { return selectedItem; } 
     set { selectedItem = value; } 
    } 

,並在您的XAML:

<ListBox ItemsSource="{Binding Sentences}" SelectedItem="{Binding SelectedItem}" Grid.Column="1" /> 
<TextBlock Text="{Binding Path=SelectedItem}" /> 
+0

不要忘記設置託管窗口的DataContext。 DataContext =「{Binding RelativeSource = {RelativeSource Self}}」 – Physikbuddha

0

您需要在文本框中指定的ElementName屬性來指定列表框中的名稱

To solve this you should change your binding to the following: 
<TextBlock ... Text="{Binding ElementName=pathListB, Path=SelectedItem.Content}" ... /> 

集列表框中屬性更新源觸發器更改爲