Specify a default empty DataTemplate instead of the default 'ToString()' DataTemplate

前端 未结 6 1341
囚心锁ツ
囚心锁ツ 2021-02-19 10:11

The default DataTemplate in a wpf application displays the result of the .ToString() method. I\'m developing an application where the default DataTemplate should di

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-19 11:17

    I discovered something accidentally. I was using a custom dependency property to set the Datacontext on a usercontrol that had a contentcontrol with Datatemplates based on types(entities in my case). Since I had several different kinds of entities my custom dependency property was

    ` typeof(object)
    

    This was the device I used to bind to the datacontext of the ContentControl.

     public object MySelectedItem
        {
            get { return (object)GetValue(Property1Property); }
            set { SetValue(Property1Property, value); }
        }
    
                public static readonly DependencyProperty Property1Property
            = DependencyProperty.Register(
                  "MySelectedItem",
                  typeof(object),
                  typeof(PromotionsMenu),
                  new PropertyMetadata(false)
              );
    

    Used like this:

     MySelectedItem = SomeEntity;
    

    I discovered I could also use it like this:

     MySelectedItem = "some text";
    

    And the contextcontrol would print some text as its context.

    MySelectedItem = "";
    

    works for a totally blank context.

    `

提交回复
热议问题