只读值的优雅解决方案 [英] Elegant Solution for Readonly Values

查看:67
本文介绍了只读值的优雅解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发WPF应用程序,其窗口大小和组件位置必须在初始化时动态计算,因为它们基于我使用的主要UserControl大小和其他一些次要大小设置。因此,目前,我已将这些常量值放在窗口代码中,如下所示:

I'm developing a WPF application whose Window size and component locations must be dynamically calculated upon initialization because they are based on the main UserControl size I use and some other minor size settings. So, for the moment, I've placed those constant values in my Window code as follows:

public const Double MarginInner = 6D;
public const Double MarginOuter = 10D;
public const Double StrokeThickness = 3D;

public static readonly Double TableHeight = (StrokeThickness * 2D) + (MarginInner * 3D) + (MyUC.RealHeight * 2.5D);
public static readonly Double TableLeft = (MarginOuter * 3D) + MyUC.RealHeight + MarginInner;
public static readonly Double TableTop = MarginOuter + MyUC.RealHeight + MarginInner;
public static readonly Double TableWidth = (StrokeThickness * 2D) + (MyUC.RealWidth * 6D) + (MarginInner * 7D);
public static readonly Double LayoutHeight = (TableTop * 2D) + TableHeight;
public static readonly Double LayoutWidth = TableLeft + TableWidth + MarginOuter;

然后,我只在XAML中使用它们,如下所示:

Then, I just use them inside my XAML as follows:

<Window x:Class="MyNS.MainWindow" ResizeMode="NoResize" SizeToContent="WidthAndHeight">
    <Canvas x:Name="m_Layout" Height="{x:Static ns:MainWindow.LayoutHeight}" Width="{x:Static ns:MainWindow.LayoutWidth}">

好吧...无话可说。它可以工作...但是很难看,我想知道是否有更好的解决方案。我不知道...也许是设置文件,绑定,内联XAML计算或其他任何东西……会使它看起来更好的东西。

Well... nothing to say. It works... but it's soooo damn ugly to see and I was wondering if there is any better solution for this. I don't know... maybe a Settings file, bindings, inline XAML calculations or whatever else... something that would make it just look better.

推荐答案

我通常将所有静态应用程序设置都放在单个称为通用类的静态或单例类中,例如 ApplicationSettings (或 MainWindowSettings (如果值仅由 MainWindow

I usually put all static my application settings in a single static or singleton class called something generic, like ApplicationSettings (or MainWindowSettings if the values are only used by the MainWindow)

它们是用户可配置的,它们进入app.config并加载到静态类的构造函数中。如果没有,我只是将它们硬编码在我的静态类中,这样以后就可以轻松找到/更改它们。

If the values are meant to be user-configurable, they go in app.config and get loaded in the constructor of the static class. If not, I just hard code them in my static class so they're easy to find/change later on.

public static class ApplicationSettings
{
    public static Double MarginInner { get; private set; }
    public static Double MarginOuter { get; private set; }
    public static Double StrokeThickness { get; private set; }

    static ApplicationSettings()
    {
        MarginInner = 6D;
        MarginOuter = 10D;
        StrokeThickness = 3D;
    }
}

对于XAML中的计算值,我通常使用 MathConverter 我写的那本书使我可以用数学写绑定表达式,然后将要使用的值传递给它。

For calculated values in your XAML, I typically use a MathConverter I wrote that lets me write a binding with a mathematical expression, and pass it the values to use.

我在博客上发布的版本只是 IValueConverter ,但很容易扩展为 IMultiValueConverter ,以便可以接受多个绑定值。

The version I have posted on my blog is only an IValueConverter, but it's pretty easy to expand into an IMultiValueConverter so it can accept multiple bound values.

<Setter Property="Height">
   <Setter.Value>
      <MultiBinding Converter="{StaticResource MathMultiConverter}"
                    ConverterParameter="(@VALUE1 * 2D) + (@VALUE2 * 3D) + (@VALUE3 * 2.5D)">
         <Binding RelativeSource="{x:Static ns:ApplicationSettings.StrokeThickness }" />
         <Binding RelativeSource="{x:Static ns:ApplicationSettings.MarginInner}" />
         <Binding ElementName="MyUc" Path="ActualHeight" />
      </MultiBinding>
   </Setter.Value>
</Setter>

通常,我会将所有这些杂乱的XAML隐藏在某个样式中,所以它不会使我混乱主要的XAML代码,只需在需要的地方应用样式即可。

Normally I would hide all this messy XAML in a Style somewhere, so it doesn't clutter up my main XAML code, and just apply the style where needed.

这是我用于 IMultiValueConvter

// Does a math equation on a series of bound values. 
// Use @VALUEN in your mathEquation as a substitute for bound values, where N is the 0-based index of the bound value
// Operator order is parenthesis first, then Left-To-Right (no operator precedence)
public class MathMultiConverter : IMultiValueConverter
{
    public object  Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        // Remove spaces
        var mathEquation = parameter as string;
        mathEquation = mathEquation.Replace(" ", "");

        // Loop through values to substitute placeholders for values
        // Using a backwards loop to avoid replacing something like @VALUE10 with @VALUE1
        for (var i = (values.Length - 1); i >= 0; i--)
            mathEquation = mathEquation.Replace(string.Format("@VALUE{0}", i), values[i].ToString());

        // Return result of equation
        return MathConverterHelpers.RunEquation(ref mathEquation);
    }

    public object[]  ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public static class MathConverterHelpers
{
    private static readonly char[] _allOperators = new[] { '+', '-', '*', '/', '%', '(', ')' };

    private static readonly List<string> _grouping = new List<string> { "(", ")" };
    private static readonly List<string> _operators = new List<string> { "+", "-", "*", "/", "%" };


    public static double RunEquation(ref string mathEquation)
    {
        // Validate values and get list of numbers in equation
        var numbers = new List<double>();
        double tmp;

        foreach (string s in mathEquation.Split(_allOperators))
        {
            if (s != string.Empty)
            {
                if (double.TryParse(s, out tmp))
                {
                    numbers.Add(tmp);
                }
                else
                {
                    // Handle Error - Some non-numeric, operator, or grouping character found in string
                    throw new InvalidCastException();
                }
            }
        }

        // Begin parsing method
        EvaluateMathString(ref mathEquation, ref numbers, 0);

        // After parsing the numbers list should only have one value - the total
        return numbers[0];
    }

    // Evaluates a mathematical string and keeps track of the results in a List<double> of numbers
    private static void EvaluateMathString(ref string mathEquation, ref List<double> numbers, int index)
    {
        // Loop through each mathemtaical token in the equation
        string token = GetNextToken(mathEquation);

        while (token != string.Empty)
        {
            // Remove token from mathEquation
            mathEquation = mathEquation.Remove(0, token.Length);

            // If token is a grouping character, it affects program flow
            if (_grouping.Contains(token))
            {
                switch (token)
                {
                    case "(":
                        EvaluateMathString(ref mathEquation, ref numbers, index);
                        break;

                    case ")":
                        return;
                }
            }

            // If token is an operator, do requested operation
            if (_operators.Contains(token))
            {
                // If next token after operator is a parenthesis, call method recursively
                string nextToken = GetNextToken(mathEquation);
                if (nextToken == "(")
                {
                    EvaluateMathString(ref mathEquation, ref numbers, index + 1);
                }

                // Verify that enough numbers exist in the List<double> to complete the operation
                // and that the next token is either the number expected, or it was a ( meaning 
                // that this was called recursively and that the number changed
                if (numbers.Count > (index + 1) &&
                    (double.Parse(nextToken) == numbers[index + 1] || nextToken == "("))
                {
                    switch (token)
                    {
                        case "+":
                            numbers[index] = numbers[index] + numbers[index + 1];
                            break;
                        case "-":
                            numbers[index] = numbers[index] - numbers[index + 1];
                            break;
                        case "*":
                            numbers[index] = numbers[index] * numbers[index + 1];
                            break;
                        case "/":
                            numbers[index] = numbers[index] / numbers[index + 1];
                            break;
                        case "%":
                            numbers[index] = numbers[index] % numbers[index + 1];
                            break;
                    }
                    numbers.RemoveAt(index + 1);
                }
                else
                {
                    // Handle Error - Next token is not the expected number
                    throw new FormatException("Next token is not the expected number");
                }
            }

            token = GetNextToken(mathEquation);
        }
    }

    // Gets the next mathematical token in the equation
    private static string GetNextToken(string mathEquation)
    {
        // If we're at the end of the equation, return string.empty
        if (mathEquation == string.Empty)
        {
            return string.Empty;
        }

        // Get next operator or numeric value in equation and return it
        string tmp = "";
        foreach (char c in mathEquation)
        {
            if (_allOperators.Contains(c))
            {
                return (tmp == "" ? c.ToString() : tmp);
            }
            else
            {
                tmp += c;
            }
        }

        return tmp;
    }
}

但说实话,如果这些值仅用于一个单一的表单,然后我只需在View后面的代码中的 Loaded 事件中设置值:)

But quite honestly, if these values are only used in a single form then I'd just set the values in the Loaded event in the code behind the View :)

这篇关于只读值的优雅解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆