因此,我在单选按钮上有一个命令,该命令绑定到 itemsource 之外的方法(即 ObservableCollection)。单击单选按钮时会产生错误。
错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'TaskSelectedCommand' property not found on 'object' ''Task' (HashCode=46555789)'. BindingExpression:Path=TaskSelectedCommand; DataItem='Task' (HashCode=46555789); target element is 'RadioButton' (Name=''); target property is 'Command' (type 'ICommand')
数据模板 XAML 代码:
<Window.Resources>
<DataTemplate x:Key="Tasks">
<StackPanel>
<Grid>
<RadioButton ToolTip="Start tracker" GroupName="rdoExchange" Grid.Row="1" Grid.Column="1" Margin="2,0,10,1" Command="{Binding TaskSelectedCommand}" IsChecked="{Binding Selected}" Height="22" VerticalAlignment="Bottom"/>
<TextBox ToolTip="Task currently being tracked" IsEnabled="true" Margin="25,15,-375,4" Grid.Row="0" Grid.Column="0" Text="{Binding Name}" RenderTransformOrigin="6.033,0.727" />
<TextBox Grid.Row="0" Margin="430,15,-455,4" Grid.Column="0" Text="{Binding Time}"/>
</Grid>
</StackPanel>
</DataTemplate>
</Window.Resources>
使用列表框上的数据模板:
<StackPanel Name="allTaskList" Orientation="Vertical" Margin="0,10,0,0">
<ListBox IsSynchronizedWithCurrentItem="True" Height="171" HorizontalAlignment="Left" ItemsSource="{Binding TaskList}"
HorizontalContentAlignment="Stretch" Margin="25,10,-523,0" VerticalAlignment="Top" Width="512" ItemTemplate="{StaticResource Tasks}"/>
</StackPanel>
Task.cs 代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace Sundial
{
public class Task
{
public int id { get; set; }
public string Name { get; set; }
public double Time { get; set; }
public bool Selected { get; set; }
}
}
MainWindowViewModel.cs 代码:
public ICommand TaskSelectedCommand
{
get
{
return mTaskSelected;
}
set
{
mTaskSelected = value;
}
}
public MainWindowViewModel()
{
TaskSelectedCommand = new RelayCommand(new Action<object>(TaskSelected));
TaskList = new ObservableCollection<Task>();
}
public void TaskSelected(object obj)
{
var task = TaskList.FirstOrDefault(i => i.Selected == true);
if (task != null)
{
timer.Start();
}
}
public void AddTask(object obj)
{
TaskList.Add(new Task() { id = taskNum, Name = "Task", Selected = false, Time = 0.0 });
}
这不是所有的代码,这只是与问题相关的代码。