我是WPF C#世界的新手。我在构造函数中有一个方法,它将子元素添加到堆栈面板中。我有2个xaml文件。 mainone有一个stackpanel,另一个有一个标签。
MainWindow查看:
<Grid Grid.Row="1" Name="VoltageChannels" >
<StackPanel Height="Auto" Name="stackPanel" Width="Auto" MinHeight="300"> </StackPanel>
</Grid>
<Button Content="Refresh All" Command="{Binding AddChildCommand}" Name="RefreshAllBtn" />
public void OnChildAdd()
{
foreach (VoltageBoardChannel mVoltageChannelViewModel in mVoltageViewModel.VoltageChannelList)
{
VoltageChannelView mVoltageChannelView = new VoltageChannelView();
mVoltageChannelView.Margin = new Thickness(2);
mVoltageChannelView.ChannelInfo = mVoltageChannelViewModel;
stackPanel.Children.Add(mVoltageChannelView);
}
}
我想从我的viewmodel类访问此方法,以通过单击按钮添加子项。基本上我有一个列表,其中包含一组项目。按钮单击时应显示这些项目:)这是View和ViewModel类:
视图模型:
public viewModel()
{
}
public List<VoltageBoardChannel> VoltageChannelList
{
get
{
return channelList;
}
set
{
channelList = value;
OnPropertyChanged("ChannelList");
}
}
List<VoltageBoardChannel> channelList = new List<VoltageBoardChannel>(0);
// VoltageBoardChannel has Channel name and avalable as property.
List<VoltageBoardChannel> redhookChannels = new List<VoltageBoardChannel>
{
new VoltageBoardChannel { ChannelName = "", IsAvailable = false},
new VoltageBoardChannel { ChannelName = "VDD_IO_AUD", IsAvailable = true},
new VoltageBoardChannel { ChannelName = "VDD_CODEC_AUD", IsAvailable = true},
new VoltageBoardChannel { ChannelName = "VDD_DAL_AUD", IsAvailable = true},
new VoltageBoardChannel { ChannelName = "VDD_DPD_AUD", IsAvailable = true},
};
private ICommand mRefreshAllCommand;
public ICommand AddChildCommand
{
get
{
if (mRefreshAllCommand == null)
mRefreshAllCommand = new DelegateCommand(new Action(mRefreshAllCommandExecuted), new Func<bool>(mRefreshAllCommandCanExecute));
return mRefreshAllCommand;
}
set
{
mRefreshAllCommand = value;
}
}
public bool mRefreshAllCommandCanExecute()
{
return true;
}
public void mRefreshAllCommandExecuted()
{
VoltageChannelList = bavaria1Channels;
// Call OnChildAdd Method here
}
XAML查看哪个有我的标签:
<Label Grid.Column="0" Content="{Binding ChannelName}" Height="25" Width="120" Name="VoltageLabel" />
VoltageBoard频道类:
public class VoltageBoardChannel
{
public string ChannelName { get; set; }
public bool IsAvailable { get; set; }
}
点击按钮时调用的方法。点击后我想调用OnChildAdd()
方法,以便将LIST
中的这些项目列表添加到我的堆栈面板中。有可能???
答案 0 :(得分:1)
在xaml:
<Button Command={Binding AddChildCommand} />
在你的viewmodel中:
public ICommand AddChildCommand { get; private set; }
然后在viewmodel的构造函数中,将AddChildCommand
设置为实现ICommand
的对象。然后,此命令可以调用您的OnChildAdd()
方法。 (here是规范)
更好的方法是将stackpanel的Children绑定到视图模型中的属性,然后将VoltageChannelView
添加到该属性中。