根据枚举更改用户控件的可见性

时间:2016-05-10 11:22:47

标签: c# wpf windows xaml user-controls

我创建了一个枚举

  public enum TaskVal
    {
    NotStarted,
    InProgress,
    Completed
    }

现在我已经在xaml中使用文本框创建了一个用户控件。我保留了所有xaml绑定路径。这看起来像

<ListView  Name="ListOfTasks"  BorderThickness="0" ScrollViewer.CanContentScroll="True" >
      <ListView.ItemTemplate>
          <DataTemplate>
             <userControls:Work Task="{Binding TaskValue=TaskValues}" />
          </DataTemplate>
      </ListView.ItemTemplate>
</ListView>

已实施的c#模型的后端是

 public class TaskModel
 {
    public TaskVal TaskValues {get;set;}
 }

这是在xaml页面中实现的登录

List<TaskVal> _list=new List<TaskVal>();
_list.Add(new TaskModel(){TaskValues=TaskVal.NotStarted});
_list.Add(new TaskModel(){TaskValues=TaskVal.InProgress});
_list.Add(new TaskModel(){TaskValues=TaskVal.NotStarted});
_list.Add(new TaskModel(){TaskValues=TaskVal.Completed});
_list.Add(new TaskModel(){TaskValues=TaskVal.InProgress});
_list.Add(new TaskModel(){TaskValues=TaskVal.NotStarted});

ListOfTasks.ItemsSource=_list;

并在usercontrol中定义了依赖属性

public TaskVal TaskValue
{
    get 
    {
       return (TaskVal)GetValue(TaskValueProperty);
    }
    set
    {
       CheckTextBoxes();
       SetValue(TaskValueProperty, value);
     }
 }



public static readonly DependencyProperty TaskValueProperty =
            DependencyProperty.Register("TaskValue", typeof(TaskVal),
              typeof(WorkUserControl), new PropertyMetadata(TaskVal.NotStarted));

和CheckTextBoxes函数是这样的东西

public void CheckTextBoxes()
{
   switch(TaskValue)
   {
      case NotStarted:
         Textbox1.Visibility=Visibility.Visible;
         TextBox2.Visibility=Visibility.Collapsed;
         TextBox3.Visibility=Visibility.Collapsed;
         break;
      case InProgress:
         Textbox1.Visibility=Visibility.Collapsed;
         TextBox2.Visibility=Visibility.Visible;
         TextBox3.Visibility=Visibility.Collapsed;
         break;
      case Completed:
         Textbox1.Visibility=Visibility.Collapsed;
         TextBox2.Visibility=Visibility.Collapsed;
         TextBox3.Visibility=Visibility.Visible;
         break;
      default:
         break;

   }
}

事情是它只使用TaskVal Enum的默认值。 TaskVal的其他值不起作用。有什么我需要注意的吗?

1 个答案:

答案 0 :(得分:0)

只有在完全加载用户控件之后才能调用CheckTextBoxes(),即在usercontrol_loaded()上调用此函数。

private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            CheckTextBoxes();
        }