视图是:
<Controls:SplitButton Margin="217,409.75,56,185" Name="SplitButton1"
Width="384"
HorizontalAlignment="Center"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Orientation="Vertical"
DisplayMemberPath ="UserName"
SelectedItem="{Binding SelectedUser,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}"
ItemsSource="{Binding Users, Mode=TwoWay}" />
ViewModel是:
public string SelectedUser
{
get { return selectedUser; }
set
{
selectedUser = value;
RaisePropertyChanged("SelectedUser");
}
}
public ObservableCollection<UserModel> Users
{
get
{
return users;
}
set
{
users = value;
}
}
模型是:
public class UserModel
{
private int id;
private string userName;
private int groupId;
private string deviceMacAddress;
public int Id { get; set; }
public string UserName { get; set; }
public int GroupId { get; set; }
public string DeviceMacAddress { get; set; }
}
我在xaml中使用上面的代码将splitbutton中的selectedItem绑定到ViewModel-&gt;属性 - SelectedUser。 但它不起作用。有谁知道为什么?
SelectedUser作为模型名称(PresentationLayer.Model.UserModel)而不是UserName prooperty返回。
答案 0 :(得分:2)
因为您的定义绑定为OneWay
。
将绑定设置为TwoWay
。
<Controls:SplitButton SelectedItem="{Binding SelectedUser,Mode=TwoWay}"/>
并且,在这种情况下无需设置UpdateSourceTrigger=PropertyChanged
,因为UpdateSourceTrigger
属性PropertyChanged
默认为SelectedItem
。