简体   繁体   English

如何在自定义wpf控件上绑定datagrid列的可见性?

[英]How can I bind visibility of a datagrid column on a custom wpf control?

I've spent the morning looking at related posts, NONE of them I've found address the exact issue I'm experiencing, although I've learned a bit more along the way. 我花了一个上午看相关的帖子,没有他们我找到了解决我正在经历的确切问题,虽然我已经学到了更多的东西。

(Using MVVM with user controls in WPF) (在MVF中使用MVVM和用户控件)

Scenario: I need to create a re-usable control which is a datagrid that shows two or three columns depending on the form requirements. 场景:我需要创建一个可重用的控件,它是一个数据网格,根据表单要求显示两列或三列。 I have a custom control I've already created, as well as a dependency property for hiding / showing this third column option: 我有一个我已经创建的自定义控件,以及用于隐藏/显示第三列选项的依赖项属性:

*Note: This visibility is dependent entirely on what I set the property to, I never need it to change based off of selection in other areas. *注意:这种可见性完全取决于我设置属性的内容,我从不需要根据其他区域的选择进行更改。

public class MyCustomControl: Control
{
    public static readonly DependencyProperty DisplayThirdColumnProperty = DependencyProperty.Register(
                                                                                        "DisplayThirdColumn",
                                                                                        typeof(bool),
                                                                                        typeof(MyCustomControl),
                                                                                        new FrameworkPropertyMetadata(false));

    static MyCustomControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
    }

    /// <summary>
    /// Gets or sets a value indicating whether the the third column should display.
    /// </summary>
    public bool DisplayThirdColumn
    {
        get
        {
            return (bool)this.GetValue(DisplayThirdColumnProperty);
        }
        set
        {
            this.SetValue(DisplayThirdColumnProperty, value);
        }
    }
}

Here is the xaml.Generic: 这是xaml.Generic:

<CheckBoxColumn Binding="{Binding StuffInThirdColumn}"
                Header="ThirdColumn" 
                Visibility="{Binding DisplayThirdColumn, 
                Converter={StaticResource BooleanToVisibilityConverter},RelativeSource={RelativeSource TemplatedParent}}"/>

Now when I consume the control: 现在当我使用控件时:

<MyControls:MyCustomControl DisplayThirdColumn="False"/>

My apologies if my 'newbieness' is showing, but am I missing something obvious here? 如果我的'新手'出现了,我很抱歉,但我错过了一些明显的东西吗? When I set the Visiblity property to collapsed explicitly on the control xaml.Generic, it correctly hides the column: 当我将Visiblity属性设置为在控件xaml.Generic上显式折叠时,它正确隐藏了列:

<CheckBoxColumn Visibility="Collapsed"..../>

Output window seems to indicate that it cant find the element to apply it to. 输出窗口似乎表明它无法找到要应用它的元素。

If I can't use relative source, do you know another way I can accomplish this? 如果我不能使用相对来源,你知道我能做到的另一种方式吗?

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。 BindingExpression:Path=DisplayThirdColumn; BindingExpression:路径= DisplayThirdColumn; DataItem=null; 的DataItem = NULL; target element is 'CheckBoxColumn' (HashCode=19379515); target元素是'CheckBoxColumn'(HashCode = 19379515); target property is 'Visibility' (type 'Visibility') 目标属性是“可见性”(类型“可见性”)

Thank you all for your comments and input, and for taking a minute (I always appreciate any time you take!) 感谢大家的意见和建议,以及花一分钟时间(我随时欢迎您的到来!)

Here is the end result, what ended up working in case someone else runs in to this: 这是最终结果,最终工作以防其他人遇到此问题:

This post helped out a lot, but the syntax I needed was missing the relative source for TemplatedParent : 这篇文章有很多帮助,但我需要的语法是缺少TemplatedParent的相关来源:

(1) I am using a consumable control, and wanted to be able to set this visibility when the control is implemented. (1)我正在使用耗材控件,并希望能够在实现控件时设置此可见性。 You can get to the ViewModel context using the steps in the post mentioned above. 您可以使用上面提到的帖子中的步骤访问ViewModel上下文。

(2) You need to put the binding Relative source to TemplatedParent on either the proxy or the dummy element (that was the part I was missing). (2)你需要在代理或虚拟元素(即我缺少的部分)上将绑定的相对源放到TemplatedParent上。

... In a ControlTemplate:

    <FrameworkElement x:Name="dummyElementToGetDataContext"
                        DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}"
                        Visibility="Collapsed" />
        <DataGrid>
           <DataGrid.Columns>
            ......
           <CheckBoxColumn Binding="{Binding SecondColumnStuff}"
                            Visibility="{Binding DataContext.ShouldDisplaySecondColumn,
                                         Converter={StaticResource BooleanToVisibilityConverter},
                                         Source={x:Reference dummyElementToGetDataContext}}"



 .............

OR 要么

Create the proxy and when declaring this as resource, set binding relative source to templated parent: 创建代理并在将此声明为资源时,将绑定相对源设置为模板化父级:

<DataGrid.Resources>
     <controls:ControlProxy x:Key="ControlProxy" Control="{Binding RelativeSource={RelativeSource TemplatedParent}}"/>
</DataGrid.Resources>

I would bind the visibility property to a boolean in the ViewModel, and use a VisibilityConverter, see http://www.codeproject.com/Tips/285358/All-purpose-Boolean-to-Visibility-Converter . 我将visibility属性绑定到ViewModel中的布尔值,并使用VisibilityConverter,请参阅http://www.codeproject.com/Tips/285358/All-purpose-Boolean-to-Visibility-Converter

This means that if the boolean property we are binding to is true , it would be converted to Visibility.Visible , and if false, Visibility.Collapsed . 这意味着如果我们绑定的boolean属性为true ,则它将转换为Visibility.Visible ,如果为false,则为Visibility.Collapsed

The Visibility property doesn't take "False" as a possible value. Visibility属性不会将“False”视为可能的值。 If you want to hide your control, you either need to write: 如果你想隐藏你的控件,你需要写:

<CheckBoxColumn Visibility="Collapsed"/>

or 要么

<CheckBoxColumn Visibility="Hidden"/>

If you want to set the Visibility in c# code, write: 如果要在c#代码中设置可见性,请写入:

yourObject.Visibility = Visibility.Collapsed;

If you need more information about the visibility property and all its possible values, you should go here: https://msdn.microsoft.com/en-us/library/system.windows.visibility(v=vs.110).aspx 如果您需要有关visibility属性及其所有可能值的更多信息,请访问: https//msdn.microsoft.com/en-us/library/system.windows.visibility(v = vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM