Mik*_*e B 6 c# data-binding wpf xaml ivalueconverter
这让我坚持不懈!
我ComboBox习惯过滤员工的查询工作正常,但只显示员工的名字.我想使用a MultiValueConverter来显示员工的全名(如果我们没有2个Mikes和2个Daves,那就不那么紧急了)
下面是我的工作代码和IMultiValueConverter类(为了简洁,修剪了不必要的格式).我已经尝试了一切我能想到的让MultiConverter工作但我没有运气.
<ComboBox ItemsSource="{Binding Path=EmployeesFilter}"
DisplayMemberPath="EmpFirstName"
SelectedValue="{Binding Path=EmployeeToShow, Mode=TwoWay}"/>
Run Code Online (Sandbox Code Playgroud)
它绑定的ViewModel属性:
// This collection is used to populate the Employee Filter ComboBox
private ObservableCollection<Employee> employeesFilter;
public ObservableCollection<Employee> EmployeesFilter
{
get {
return employeesFilter;
}
set {
if (employeesFilter != value)
{
employeesFilter = value;
OnPropertyChanged("EmployeesFilter");
}
}
}
// This property is TwoWay bound to the EmployeeFilters SelectedValue
private Employee employeeToShow;
public Employee EmployeeToShow
{
get {
return employeeToShow;
}
set {
if (employeeToShow != value)
{
employeeToShow = value;
OnPropertyChanged("EmployeeToShow");
QueryIssues(); // Requery with new employee filter
}
}
}
Run Code Online (Sandbox Code Playgroud)
IMultiValueConverter:
class StringsToFullNameMultiConverter : IMultiValueConverter
{
public object Convert(object[] values,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
// I added this because I kept getting DependecyProperty.UnsetValue
// Passed in as the program initializes
if (values[0] as string != null)
{
string firstName = (string)values[0];
string lastName = (string)values[1];
string fullName = firstName + " " + lastName;
return fullName;
}
return null;
}
public object[] ConvertBack(object value,
Type[] targetTypes,
object parameter,
System.Globalization.CultureInfo culture)
{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了很多不同的东西,但基本上我在ComboBox中使用以下内容
<ComboBox.SelectedValue>
<MultiBinding Converter="{StaticResource StringsToFullNameMultiConverter}"
Mode="OneWay" >
<Binding Path="EmpFirstName" />
<Binding Path="EmpLastName"/>
</MultiBinding>
</ComboBox.SelectedValue>
Run Code Online (Sandbox Code Playgroud)
现在,当程序使用设置为的值进行初始化时,将调用转换器DependencyProperty.UnsetValue.之后,即使从盒子中选择一个名字,它也永远不会被再次调用.名称仍显示为名字.
感谢您提供的任何帮助或指向优秀教程/示例的指示.我在网上发现的所有内容都是文本框,我可以整天使用它们.
Jos*_*osh 21
你很亲密!你想做的ComboBox.ItemTemplate不是SelectedValue.准备一些XAML地狱.
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource StringsToFillNameMultiConverter}">
<Binding Path="EmpFirstName" />
<Binding Path="EmpLastName" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)
另外,如果我没记错的话,如果你只是格式化字符串,则不需要创建自己的转换器.我想你可以做以下事情(如果我错了,请有人纠正我.)
<!-- "Last, First" -->
<MultiBinding StringFormat="{}{1}, {0}">
<Binding Path="EmpFirstName" />
<Binding Path="EmpLastName" />
</MultiBinding>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25675 次 |
| 最近记录: |