问题描述
好的,这里有好几个问题
首先
这是我的实施,但它不起作用我怎样才能使它工作?
Ok here several questions
First
This is my implementation but it is not working atm how can i make it work ?
<Grid> // xaml part
<Button Content="Start Crawling Root Sites - This Deletes All Data" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="279" Command="{Binding StartCrawling}" Click="click_start_Crawling" />
<ListBox Name="lstBoxEvents" HorizontalAlignment="Left" Height="138" Margin="294,10,0,0" VerticalAlignment="Top" Width="312">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="1" Text="{Binding ocEvents}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
private void click_start_Crawling(object sender, RoutedEventArgs e) // inside mainwindow
{
PublicStaticFunctions.AddMsgToEvents("trial");
}
public static class PublicStaticFunctions // seperate class
{
public static ObservableCollection<string> ocEvents = new ObservableCollection<string>();
public static void AddMsgToEvents(string srMessage)
{
ocEvents.Insert(0, srMessage);
}
}
运行时的第二个问题多线程,如果多个线程访问AddMsgToEvents函数并添加变量,列表框是否会自动刷新而没有任何问题?
非常感谢
My second question when running multithreaded, if multiple threads access AddMsgToEvents function and adds variable, would listbox still auto refresh without any problem ?
Thank you very much
推荐答案
<listbox itemssource="{Binding Components, Mode=OneWay}" />
<listbox name="lstBoxEvents" horizontalalignment="Left" height="138" margin="294,10,0,0" verticalalignment="Top" width="312" itemssource="{Binding ocEvents}">
<listbox.itemtemplate>
<datatemplate>
<grid margin="1">
<grid.columndefinitions>
<columndefinition width="Auto" />
</grid.columndefinitions>
<textblock grid.column="1" text="{Binding Path=ocEvent}" />
</grid>
</datatemplate>
</listbox.itemtemplate>
</listbox>
其中ocEvent是一个字符串类型的字段
第二期
如果你正在使用多线程然后会出现问题,因为一个线程锁定的资源不能被其他线程使用。要解决此问题,您需要使用
where ocEvent is a field of type string
for the second issue
if you are using multithreads then there will be issue because a resource locked by one thread cannot be used by other thread. To resolve this you need to use
Application.Current.Dispatcher.Invoke(new Action(delegate
{
ocEvents.Insert(0, srMessage);
}));
这篇关于如何绑定和自动更新列表框wpf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!