我正在研究Silverlight,我是新手,我有一个combox框,里面有一个复选框和文本框。我想在按钮点击时获得这些控件的值,我该如何在SilverLight中执行此操作? 这是我的ComboBox
<ComboBox x:Name="Type" VerticalAlignment="Top" Margin="2,8,-2,0" Grid.ColumnSpan="3" Height="28" Padding="3">
<ComboBoxItem>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*" MinWidth="105" />
<ColumnDefinition Width="60" />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="true" VerticalAlignment="Center" Grid.Column="0"/>
<TextBlock Text="All" VerticalAlignment="Center" Grid.Column="1" Style="{x:Null}" FontSize="11"/>
</Grid>
</ComboBoxItem>
<ComboBoxItem>
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*" MinWidth="105" />
<ColumnDefinition Width="60" />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="true" VerticalAlignment="Center" Grid.Column="0"/>
<TextBlock Text="General" VerticalAlignment="Center" Grid.Column="1" Style="{x:Null}" FontSize="11"/>
<TextBox Text="25" VerticalAlignment="Center" Grid.Column="2" FontSize="11" Padding="2" HorizontalContentAlignment="Right"/>
</Grid>
</ComboBoxItem>
</ComboBox>
用户可以选择多个值 我正在使用MVVM模式
答案 0 :(得分:1)
由于您的所有ComboBox项目都不变,您可以为这些项目指定名称并直接引用它们。
<ComboBoxItem x:Name="ComboItemAll">
...
</ComboBoxItem>
<ComboBoxItem x:Name="ComboItemGeneral">
...
</ComboBoxItem>
和按钮点击事件:
if (ComboItemAll.IsSelected)
{
...
}
else if (ComboItemGeneral.IsSelected)
{
...
}
或者,您也可以从ComboBox“Type”中获取此信息:
var selectedItem = Type.SelectedItem;
if (selectedItem.Name.StartsWith("ComboItemAll"))
{
...
}
else if (selectedItem.Name.StartsWith("ComboItemGeneral"))
{
...
}
对于MVVM (编辑):
Xaml(查看):
<ComboBox SelectedItem="{Binding SelectedCustomItem, Mode=TwoWay}" ItemsSource="{CustomItems}" ItemTemplate={StaticResource CustomItemsTemplate} />
Xaml(资源):
<DataTemplate x:Key="CustomItemsTemplate">
<StackPanel
<CheckBox IsChecked="{Binding IsSelected}" VerticalAlignment="Center"/>
<TextBlock Text="{Binding CustomPropertyFromCustomClass}"/>
</StackPanel>
</DataTemplate>
VM:
public class ViewModel
{
public ViewModel()
{
CustomItems = new ObservableCollection<CustomClass>();
CustomItems.Add(new CustomClass() { "All" });
CustomItems.Add(new CustomClass() { "General" });
}
private ObservableCollection<CustomClass> customItems = null;
public ObservableCollection<CustomClass> CustomItems
{
get { return customItems; }
set
{
if (object.Equals(value, customItems) == false)
{
customItems = value;
OnPropertyChanged(() => CustomItems);
}
}
}
private CustomClass selectedCustomItem = null;
public CustomClass SelectedCustomItem
{
get { return selectedCustomItem; }
set
{
if (object.Equals(value, selectedCustomItem) == false)
{
selectedCustomItem= value;
OnPropertyChanged(() => SelectedCustomItem);
}
}
}
}
您不应该直接从ViewModel引用您的组合框。 ViewModel中的所有内容都应该与数据操作相关,并且对View(也就是ComboBox)一无所知。
其他一切都应该在视图中完成。如果你需要访问ComboBox,你需要问自己为什么,我可以通过模板和绑定在XAML中做这个逻辑吗?