我很抱歉奇怪的头衔。我正在处理动态生成Ui组件。我的Xaml类中有一个ListBox,它可以动态生成按钮。
查看:
<ListBox x:Name="SetButtonList" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate >
<Grid>
<Button Content="{Binding Path=SetButtonFreq}" Command="{Binding Path=SetFreqCommand}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
视图模型:
private ICommand mSetFreqCommand;
public ICommand SetFreqCommand
{
get
{
if (mSetFreqCommand == null)
mSetFreqCommand = new DelegateCommand(new Action(SetFreqCommandExecuted), new Func<bool>(SetFreqCommandCanExecute));
return mSetFreqCommand;
}
set;
}
public bool SetFreqCommandCanExecute()
{
return true;
}
public void SetFreqCommandExecuted()
{
// Executes the Body when Button is Clicked
}
型号:
private string _SetFreqValue = "";
public String SetButtonFreq
{
set; get;
}
public ClockModel(string SetButtonFreq)
{
this.SetButtonFreq = SetButtonFreq;
}
public override string ToString()
{
return _SetFreqValue;
}
View.cs文件:
// mClock is object of Model Class
mClock.Add(new ClockModel("Set 12.0 MHz"));
mClock.Add(new ClockModel("Set 12.288 MHz"));
mClock.Add(new ClockModel("Set 15.36 MHz"));
mClock.Add(new ClockModel("Set 19.2 MHz"));
这给了我列表框中4个不同频率的按钮。但是当我尝试单击它们时,控件不会进入SetFreqCommandExecuted()
方法。我在哪里弄错了? :(
请帮忙
答案 0 :(得分:2)
该按钮尝试在绑定项目内找到 SetFreqCommand ,而不是在当前页面的常规 ViewModel 中找到。您可以使用此绑定来修复它:
Command="{Binding ElementName=SetButtonList, Path=DataContext.SetFreqCommand}"