新建用户控件:MilutSelect
XAML:
<Grid x:Name="LayoutRoot" Background="White">
<ComboBox x:Name="chkTest" MinHeight="20"
DropDownopened="chkTest_DropDownopened" DropDownClosed="chkTest_DropDownClosed">
</ComboBox>
</Grid>
后台代码:
public partial class MilutSelect : UserControl
{
private string _SelectValue;
/// <summary>
/// 选择的值
/// </summary>
public string SelectValue
{
get { return _SelectValue; }
}
public MilutSelect()
{
InitializeComponent();
}
/// <summary>
/// 设置选择项
/// </summary>
/// <param name="values"></param>
public void SetSelectValue(IList<string> values)
{
CheckList.Clear();
if (values != null && values.Count > 0)
{
_SelectValue = string.Join(",",values);
if (chkTest.Items != null && chkTest.Items.Count > 0)
{
foreach (var item in chkTest.Items)
{
if (item is CheckBox)
{
var ck = item as CheckBox;
if (values.Contains(ck.Content.ToString()))
{
ck.IsChecked = true;
CheckList.Add(ck);
}
}
}
}
}
bindCalues();
}
/// <summary>
/// 数据绑定
/// </summary>
/// <param name="dataSource"></param>
public void BindDataSource(IList<string> dataSource)
{
if (dataSource != null && dataSource.Count > 0)
{
IList<ComboBoxItem> list=new List<ComboBoxItem>();
foreach (var item in dataSource)
{
var bi = new CheckBox { Content = item};
bi.Click += CheckBox_Click;
chkTest.Items.Add(bi);
}
chkTest.Items.Add(new ComboBoxItem());
}
}
private List<CheckBox> CheckList = new List<CheckBox>();
private void CheckBox_Click(object sender,RoutedEventArgs e)
{
if ((sender as CheckBox).IsChecked == true)
{
CheckList.Add(sender as CheckBox);
}
else
{
CheckList.Remove(sender as CheckBox);
}
}
private void chkTest_DropDownopened(object sender,EventArgs e)
{
chkTest.Items.RemoveAt(chkTest.Items.Count - 1);
}
private void chkTest_DropDownClosed(object sender,EventArgs e)
{
bindCalues();
}
private void bindCalues()
{
string name = "";
foreach (var one in CheckList)
{
name += one.Content + ",";
}
if (name.Length > 0)
name = name.Remove(name.Length - 1);
chkTest.Items.Add(new ComboBoxItem() { Content = name.ToString() });
_SelectValue = name;
chkTest.Selectedindex = chkTest.Items.Count - 1;
}
}
调用时:
页面引用用户控件,x:name:msl
msl.BindDataSource(new List<string>(){“1”,"2","3","4","5"});//绑定数据 msBussiness.SetSelectValue((new List<string>(){“1”,"2"});设置选择项
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。