C# 如何允许宽度=”;“自动”;在自定义WPF控件中

C# 如何允许宽度=”;“自动”;在自定义WPF控件中,c#,wpf,xaml,C#,Wpf,Xaml,我基于Expander类创建了一个自定义控件: public partial class HideableExpander : Expander { public new double Height { get { if (Visibility== System.Windows.Visibility.Hidden) { return 0; }

我基于Expander类创建了一个自定义控件:

public partial class HideableExpander : Expander
{
    public new double Height
    {
        get
        {
            if (Visibility== System.Windows.Visibility.Hidden)
            {
                return 0;
            }
            return base.Height;
        }
        set
        {
            base.Height = value;
        }
    }

    public new double Width
    {
        get
        {
            if (Visibility == System.Windows.Visibility.Hidden)
            {
                return 0;
            }
            return base.Width;
        }
        set
        {
            base.Width = value;
        }
    }

    public new Thickness Margin
    {
        get
        {
            if (Visibility== System.Windows.Visibility.Hidden)
            {
                return new Thickness();
            }
            return base.Margin;
        }
        set
        {
            base.Margin = value;
        }
    }

    public HideableExpander()
    {

        this.InitializeComponent();

    }
}
XAML:


现在,当我尝试使用Width=“Auto”属性时:

            <local:HideableExpander Header="{Binding Expander1Name, ElementName=Window}"  Margin="10" Width="Auto" Background="#00F19494" VerticalAlignment="Top" >
                <WrapPanel Height="Auto" Margin="0" Width="Auto" >
                      <TextBlock Text="Please, enter the name of this expander:       " VerticalAlignment="Center"/>
                      <TextBox Width="150" Text="{Binding Expander1Name, ElementName=Window, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" Background="#FFF5EECC"/>  
                </WrapPanel>
            </local:HideableExpander>

我遇到一个异常,无法将“自动”转换为双精度:

Unhandled Exception: System.Windows.Markup.XamlParseException: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '10' and line position '8'. ---> System.Exception: Auto is not a valid value for Double. ---> System.FormatException: Input string was not in a correct format.
   at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
   at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider)
   at System.ComponentModel.DoubleConverter.FromString(String value, NumberFormatInfo formatInfo)
   at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
   --- End of inner exception stack trace ---
   at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
   at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue(MarkupExtension me, IServiceProvider serviceProvider)
   --- End of inner exception stack trace ---
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
   at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
   at System.Windows.Application.DoStartup()
   at System.Windows.Application.<.ctor>b__1(Object unused)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run()
   at leartWPF.App.Main() in d:\Users\menkaur\Documents\Expression\Blend 4\Projects\leartWPF\leartWPF\obj\Debug\App.g.cs:line 0
未处理的异常:System.Windows.Markup.XamlParseException:“在”System.Windows.Baml2006.TypeConverterMarkupExtension“上提供值”引发了异常。“行号“10”和行位置“8”。-->System.Exception:Auto不是Double的有效值。-->System.FormatException:输入字符串的格式不正确。
在System.Number.ParseDouble(字符串值、NumberStyles选项、NumberFormatInfo numfmt)
在System.Double.Parse(字符串s、NumberStyles样式、IFormatProvider)
位于System.ComponentModel.DoubleConverter.FromString(字符串值,NumberFormatInfo formatInfo)
位于System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext上下文、CultureInfo区域性、对象值)
---内部异常堆栈跟踪的结束---
位于System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext上下文、CultureInfo区域性、对象值)
位于MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProviderValue(MarkupExtension me,IServiceProvider服务提供者)
---内部异常堆栈跟踪的结束---
在System.Windows.Markup.WpfXamlLoader.Load(XamlReader XamlReader、IXamlObjectWriterFactory writerFactory、Boolean skipJournaledProperties、Object rootObject、XamlObjectWriterSettings设置、Uri baseUri)
位于System.Windows.Markup.wpfxamloader.LoadBaml(XamlReader XamlReader、Boolean skipJournaledProperties、Object rootObject、XamlAccessLevel accessLevel、Uri baseUri)
位于System.Windows.Markup.XamlReader.LoadBaml(Stream-Stream,ParserContext-ParserContext,Object-parent,Boolean-closeStream)
在System.Windows.Application.LoadBamlStreamWithSyncInfo(流,ParserContext pc)
位于System.Windows.Application.LoadComponent(Uri resourceLocator,布尔bSkipJournaledProperties)
在System.Windows.Application.DoStartup()中
在System.Windows.Application.b__1(未使用的对象)
位于System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托回调、对象参数、Int32 numArgs)
位于MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(对象源、委托方法、对象参数、Int32 numArgs、委托catchHandler)
位于System.Windows.Threading.Dispatcher.WrappedInvoke(委托回调、对象args、Int32 numArgs、委托catchHandler)
在System.Windows.Threading.DispatcherOperation.InvokeImpl()中
位于System.Threading.ExecutionContext.runTryCode(对象用户数据)
在System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode代码、CleanupCode backoutCode、Object userData)中运行
在System.Threading.ExecutionContext.Run(ExecutionContext ExecutionContext,ContextCallback回调,对象状态,布尔ignoreSyncCtx)
在System.Threading.ExecutionContext.Run(ExecutionContext ExecutionContext,ContextCallback回调,对象状态)
在System.Windows.Threading.DispatcherOperation.Invoke()中
在System.Windows.Threading.Dispatcher.ProcessQueue()中
位于System.Windows.Threading.Dispatcher.WndProcHook(IntPtr-hwnd、Int32-msg、IntPtr-wParam、IntPtr-lParam、Boolean和handled)
在MS.Win32.HwndWrapper.WndProc(IntPtr-hwnd、Int32-msg、IntPtr-wParam、IntPtr-lParam、Boolean和handled)
在MS.Win32.HwndSubclass.DispatcherCallbackOperation(对象o)上
位于System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托回调、对象参数、Int32 numArgs)
位于MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(对象源、委托方法、对象参数、Int32 numArgs、委托catchHandler)
位于System.Windows.Threading.Dispatcher.WrappedInvoke(委托回调、对象args、Int32 numArgs、委托catchHandler)
位于System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority优先级、TimeSpan超时、委托方法、对象参数、Int32 numArgs)
位于MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd、Int32 msg、IntPtr wParam、IntPtr lParam)
位于MS.Win32.unsafentivemethods.DispatchMessage(MSG&MSG)
位于System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame框架)
位于System.Windows.Application.RunInternal(窗口)
在System.Windows.Application.Run()处
在d:\Users\menkaur\Documents\Expression\Blend 4\Projects\leartWPF\leartWPF\obj\Debug\App.g.cs中的leartWPF.App.Main()处:第0行
我应该怎么做才能接受自动作为值?

您需要在属性上使用,指定应使用<代码>自动然后转换为
双精度.NaN

(您可以在
FrameworkElement
属性上看到这一操作,并且)

您需要在属性上使用,指定应使用<代码>自动然后转换为
双精度.NaN


(您可以在
FrameworkElement
properties上看到这一点,

尝试添加以下属性,我认为这应该会有所帮助,当然,“new”可以隐藏父对象的宽度

[TypeConverterAttribute(typeof(LengthConverter))]
public new double Width
{
  ......your getter and setter
//编辑 每一条评论:-“什么是getter和setter?”


尝试添加以下属性,我认为这应该会有所帮助,当然,“新建”可以隐藏父对象的宽度

[TypeConverterAttribute(typeof(LengthConverter))]
public new double Width
{
  ......your getter and setter
//编辑 每一条评论:-“什么是getter和setter?”


那么设置Visibility=Collapsed有什么错呢?那么设置Visibility=Collapsed有什么错呢?对不起,对于我们这些WPF新手来说,你能给我们展示一下getter和setter中的示例吗;它们是如何使用的?get/set是公开属性的访问器,可以将它们看作是对类中某个私有字段的读/写。原因-私有变量、状态、控件的封装。您不希望您的类的用户直接访问它,也许您添加了
   //getter and setter sample(grabbing them from the question)
    get
    {
        if (Visibility == System.Windows.Visibility.Hidden)
        {
            return 0;
        }
        return base.Width;
    }
    set
    {
        base.Width = value;
    }
}