我将Active Directory中的用户添加到我的ListBox
。
我从Active Directory获取的对象是SearchResult
,这是我添加到ListBox
的内容。问题是我不知道如何显示为SearchResult对象属性的文本值。
ListBox
显示“System.DirectoryServices.SearchResult”,而我想显示“John Smith”(我的SearchResult对象中的“cn”属性)
这是我的代码:
XAML:
<telerik:RadListBox Grid.Column="2" Grid.Row="2" SelectionMode="Multiple" x:Name="SearchListbox" Margin="5 5 5 0" Height="100"/>
<telerik:RadListBox Grid.Column="4" Grid.Row="2" SelectionMode="Multiple" x:Name="AddListbox" Margin="5 5 5 0" Height="100"/>
CS:
DirectorySearcher searcher = new DirectorySearcher(entry.Path)
{
Filter = "(&(cn*)(sn=*)(mail=*)(givenName=*))"
};
var results = searcher.FindAll();
foreach (SearchResult result in results)
{
SearchListBox.Items.Add(result);
}
我无法使用ItemSource
,因为我想将对象从一个ListBox
转移到另一个ItemSource
我不能简单地从ListBox
删除对象。< / p>
知道如何处理吗?
更新,解决了没有改变ObservableCollection的问题:
完整的工作代码:
private ObservableCollection<SearchResult> resultsSearch = new ObservableCollection<SearchResult>();
private ObservableCollection<SearchResult> resultsAdd = new ObservableCollection<SearchResult>();
public ObservableCollection<SearchResult> ResultsSearch
{
get { return resultsSearch; }
set { resultsSearch = value; }
}
public ObservableCollection<SearchResult> ResultsAdd
{
get { return resultsAdd; }
set { resultsAdd = value; }
}
public event PropertyChangedEventHandler PropertyChanged;
public event NotifyCollectionChangedEventHandler CollectionChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
protected virtual void OnCollectionChange(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
CollectionChanged(this, e);
}
public void Add(SearchResult item)
{
this.ResultsSearch.Add(item);
this.OnCollectionChange(
new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Add, item));
}
public void Remove(SearchResult item)
{
this.ResultsSearch.Remove(item);
this.OnCollectionChange(
new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Remove, item));
}
答案 0 :(得分:0)
要显示您必须设置ItemTemplate
属性的用户名:
<telerik:RadListBox x:Name="SearchListbox" Grid.Column="2" Grid.Row="2"
SelectionMode="Multiple" Margin="5 5 5 0" Height="100">
<telerik:RadListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Properties[cn]}"/>
</DataTemplate>
</telerik:RadListBox.ItemTemplate>
</telerik:RadListBox>
最佳做法是围绕SearchResult
模型创建一个ViewModel类。在这种情况下,您的ViewModel将声明一个FullName
属性,该属性将访问模型中的字典以获取实际值:
<强> SearchResultViewModel.cs 强>
public string FullName
{
get { return searchResult.Properties["cn"];}
}
您应该避免将View与业务逻辑捆绑在一起。使用上面的ViewModel,绑定看起来像Text="{Binding FullName}"
,这样就无需创建复杂的绑定。
我无法使用ItemSource,因为我想从一个传输对象 ListBox到另一个和itemSource我不能删除对象 来自ListBox。
是的,您可以使用ObservableCollection
作为ItemsSource
。当您对此集合进行更改时,将更新UI。