C# 无法强制转换类型为';System.Windows.Data.Binding';输入';系统字符串
你好,我收到这个错误 对与指定绑定约束匹配的类型“System.Windows.Data.Binding”调用构造函数时引发异常。 {“无法将类型为'System.Windows.Data.Binding'的对象强制转换为类型为'System.String'。” 我下面有一门单选按钮课C# 无法强制转换类型为';System.Windows.Data.Binding';输入';系统字符串,c#,wpf,mvvm,C#,Wpf,Mvvm,你好,我收到这个错误 对与指定绑定约束匹配的类型“System.Windows.Data.Binding”调用构造函数时引发异常。 {“无法将类型为'System.Windows.Data.Binding'的对象强制转换为类型为'System.String'。” 我下面有一门单选按钮课 public class GroupedList { public string Group { get; set; } public bool IsSelected { get; set; }
public class GroupedList
{
public string Group { get; set; }
public bool IsSelected { get; set; }
}
然后在我的视图模型中,我有一个此类的可观察集合
/// <summary>
/// The <see cref="GroupList" /> property's name.
/// </summary>
public const string GroupListPropertyName = "GroupList";
private ObservableCollection<GroupedList> _groupList = new ObservableCollection<GroupedList>();
/// <summary>
/// Sets and gets the GroupList property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public ObservableCollection<GroupedList> GroupList
{
get { return _groupList; }
set { Set(GroupListPropertyName, ref _groupList, value); }
}
//
///该属性的名称。
///
public const string GroupListPropertyName=“GroupList”;
私有ObservableCollection_groupList=新ObservableCollection();
///
///设置并获取GroupList属性。
///更改该属性的值将引发PropertyChanged事件。
///
公共可观测集合组列表
{
获取{return\u groupList;}
set{set(GroupListPropertyName,ref _groupList,value);}
}
在我看来,我有一个带有单选按钮的组合框作为模板。ComboBox ItemSource已设置为集合。Content和IsCheckedProperties设置为类中的两个属性
<ComboBox Name="groupCombo" ItemsSource="{Binding GroupList}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="GroupButton"
GroupName="Options1"
Content="{Binding Group}"
IsChecked="{Binding IsSelected}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<command:EventToCommand Command="{Binding
{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type UserControl}}, Path=DataContext.GroupChecked}}"
CommandParameter="{Binding Content,ElementName=GroupButton}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</RadioButton>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
我添加了事件触发器,以尝试访问视图模型中下面的relay命令中选中事件的content属性
private RelayCommand<string> _groupChecked;
/// <summary>
/// Gets the GroupChecked.
/// </summary>
public RelayCommand<string> GroupChecked
{
get
{
return _groupChecked
?? (_groupChecked = new RelayCommand<string>(
x =>
{
if (!string.IsNullOrWhiteSpace(x))
{
//DoStuff
}
}));
}
}
private RelayCommand\u groupChecked;
///
///获取已检查的组。
///
公共中继命令组已检查
{
得到
{
返回\u组已选中
??(_groupChecked=新继电器命令(
x=>
{
如果(!string.IsNullOrWhiteSpace(x))
{
//多斯塔夫
}
}));
}
}
添加命令后,错误正在发生,我想,但不确定它是否抛出,因为这一行
CommandParameter=“{Binding Content,ElementName=GroupButton}”/>
我想知道我是否可以在尝试时用relay命令完成这一点。感谢您的中继命令是类型为
的泛型命令,因此它试图将绑定从命令参数强制转换为字符串
这里的内容将是一个框架元素,由当时可用的数据模板决定
使继电器命令成为继电器命令RelayCommand
。在relay命令的匿名方法中,x.GetType
将告诉您在那里设置了什么内容
希望这能消除你的疑虑