65.9K
CodeProject 正在变化。 阅读更多。
Home

WPF 边距计算器控件

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.67/5 (3投票s)

2010 年 9 月 7 日

CPOL

2分钟阅读

viewsIcon

31220

downloadIcon

354

.NET 4.0 WPF 控件,允许您输入成本和售价,并计算利润率。

引言

这是一个我最近为一个项目创建的 WPF 用户控件。

它非常简单,您输入成本和可选的售价,它会告诉您应该以什么价格出售该商品,以及您将获得的利润和收益。

该控件的 UI 由一些基本的 WPF 控件组成,并包含一些简单的渐变背景。

还有一个很酷的玻璃按钮,位于 UserControl.Resources 部分。
您可以获取玻璃按钮的控件模板并根据您的需要进行自定义。

我已在代码下载中包含了一个演示应用程序,以及下面的截图。

MarginCalculator.png

Using the Code

要使用此控件,只需在 Visual Studio 的工具箱中右键单击并添加对
CodeLogix.Controls.MarginCalculator 命名空间的引用。

这将把控件添加到工具箱,并允许您将其拖放到 WPF 设计图面上。

注意: 我还包含了一个简单的仅数字文本框,用于 WPF。

这将允许您仅输入数字和小数分隔符到成本和售价字段中。

它的代码非常简单,我们只需子类化 System.Windows.Controls.TextBox 类并重写 OnPreviewTextInput 方法。然后我们需要创建一个辅助方法来验证有效输入。

仅数字文本框代码

   protected override void OnPreviewTextInput
	(System.Windows.Input.TextCompositionEventArgs e)
    {
        e.Handled = !AreAllValidNumericChars(e.Text);
        base.OnPreviewTextInput(e); 
    }
    
    static bool AreAllValidNumericChars(string str)
    {
        bool ret = true;
        if (str == System.Globalization.NumberFormatInfo.CurrentInfo.
		CurrencyDecimalSeparator |                
            str == System.Globalization.NumberFormatInfo.
		CurrentInfo.NumberDecimalSeparator)
            
            return ret;
            
        int l = str.Length;
        for (int i = 0; i < l; i++)
        {
            char ch = str[i];
            ret &= Char.IsDigit(ch);
        }
        
        return ret;
    }
}

利润率计算器代码

public partial class MarginCalculator : UserControl
{       
    public MarginCalculator()
    {
        InitializeComponent();
    }
    
    // This is used to store the values for the different margin textBlock controls.
    internal struct MarginValues
    {           
        public double TwentyFivePercent { get; set; }
        public double ThirtyPercent { get; set; }
        public double ThirtyFivePercent { get; set; }
        public double FortyPercent { get; set; }
        public double FortyFivePercent { get; set; }
        public double FiftyPercent { get; set; }
        public double FiftyFivePercent { get; set; }
        public double SixtyPercent { get; set; }
        public double SixtyFivePercent { get; set; }
    }
    
    // Here we calculate the profit margin, by subtracting the sale price, 
    // minus the cost, divided by the sale price. 
    
    private static double CalculateProfitMargin(double cost, double salePrice)
    {
        return (salePrice - cost) / salePrice;
    }
    
    private static MarginValues CalculateMargin(double costOfPart)
    {
        MarginValues values = new MarginValues 
        { 
            TwentyFivePercent = Math.Round(((1 - Convert.ToDouble(costOfPart)) / (-0.73))), 
            ThirtyPercent     = Math.Round(((1 - Convert.ToDouble(costOfPart)) / (-0.68))), 
            ThirtyFivePercent = Math.Round(((1 - Convert.ToDouble(costOfPart)) / (-0.63))), 
            FortyPercent      = Math.Round(((1 - Convert.ToDouble(costOfPart)) / (-0.58))), 
            FortyFivePercent  = Math.Round(((1 - Convert.ToDouble(costOfPart)) / (-0.53))), 
            FiftyPercent      = Math.Round(((1 - Convert.ToDouble(costOfPart)) / (-0.49))), 
            FiftyFivePercent  = Math.Round(((1 - Convert.ToDouble(costOfPart)) / (-0.44))), 
            SixtyPercent      = Math.Round(((1 - Convert.ToDouble(costOfPart)) / (-0.39))), 
            SixtyFivePercent  = Math.Round(((1 - Convert.ToDouble(costOfPart)) / (-0.34))) 
        };
        return values;
    }
    
    // Here we check for valid input and compute the results. 
    private void RunCalculations()
    {
        MarginValues results = new MarginValues();
        if (!String.IsNullOrEmpty(textBoxCostOfPart.Text))
        {
            double cost;
            if (double.TryParse(textBoxCostOfPart.Text, out cost))
            {
                results = CalculateMargin(cost);
                if (!String.IsNullOrEmpty(textBoxSalePrice.Text))
                {
                    double salePrice;
                    if (double.TryParse(textBoxSalePrice.Text, out salePrice))
                    {
                        double profitMargin = CalculateProfitMargin(cost, salePrice);
                        margin.Text = profitMargin.ToString("p");
                        double profit = salePrice - cost;
                        this.profit.Text = profit.ToString("c");
                    }
                }
            }
        }
        // set the percent textblocks
        twentyFivePercent.Text = results.TwentyFivePercent.ToString("c");
        thirtyPercent.Text     = results.ThirtyPercent.ToString("c");
        thirtyFivePercent.Text = results.ThirtyFivePercent.ToString("c");
        fortyPercent.Text      = results.FortyPercent.ToString("c");
        fortyFivePercent.Text  = results.FortyFivePercent.ToString("c");
        fiftyPercent.Text      = results.FiftyPercent.ToString("c");
        fiftyFivePercent.Text  = results.FiftyFivePercent.ToString("c");
        sixtyPercent.Text      = results.SixtyPercent.ToString("c");
        sixtyFivePercent.Text  = results.SixtyFivePercent.ToString("c");
    }
    
     // The rest of the code simply invokes the calculation code,
    // whenever a user clicks the GO button, or types valid input into the
    // Cost or Sale Price textBox.
    private void buttonCalculate_Click(object sender, RoutedEventArgs e)
    {
       RunCalculations();
    }
     
    private void textBoxCostOfPart_KeyDown(object sender, KeyEventArgs e)
    {
        RunCalculations();
    }
    
    private void textBoxSalePrice_KeyDown(object sender, KeyEventArgs e)
    {
        RunCalculations();
    }
    
    private void textBoxCostOfPart_GotFocus(object sender, RoutedEventArgs e)
    {
        textBoxCostOfPart.SelectAll();
    }
    
    private void textBoxSalePrice_GotFocus(object sender, RoutedEventArgs e)
    {
        textBoxSalePrice.SelectAll();
    }
    
    private void textBoxSalePrice_GotMouseCapture(object sender, MouseEventArgs e)
    {
        textBoxSalePrice.SelectAll();
    }
    
    private void textBoxCostOfPart_GotMouseCapture(object sender, MouseEventArgs e)
    {
        textBoxCostOfPart.SelectAll();
    }
}

如果有人觉得此控件有用和/或有改进方法,请留下评论告诉我。

值得关注的点 (工具箱图标)

我做的一件事是将自定义图标添加到 Visual Studio 工具箱中的控件。如果有人不确定如何操作,我来解释一下。

  1. 首先,您需要在与用户控件相同的级别添加一个图像到您的项目中。
  2. 然后确保将图像重命名为 UserControlName.Icon.YourImageExtension
  3. 接下来,确保将图像设置为嵌入式资源,在属性窗口中。

注意: 您的自定义图标不会显示在自动添加的工具箱项中。

您需要 右键单击添加项,然后浏览到您的用户控件的程序集并将其添加到工具箱。

然后一切都会按预期工作。

历史

  • 2010/9/2:上传了控件的第一个版本
© . All rights reserved.