Hiển thị các bài đăng có nhãn C#. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn C#. Hiển thị tất cả bài đăng

Chủ Nhật, 9 tháng 6, 2013

Code C#: Thêm Ellipse, TextBlock vào cây (Tree)


<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      HorizontalAlignment="Center" VerticalAlignment="Center">
<TreeView>
  <TreeViewItem Header="A" IsExpanded="True">
    <TreeViewItem Header="B" />
    <TreeViewItem Header="C" IsExpanded="True">
      <TreeViewItem Header="D" />
      <TreeViewItem Header="E" />
    </TreeViewItem>
    <TreeViewItem Header="F" />
  </TreeViewItem>
  <TreeViewItem IsExpanded="True">
    <TreeViewItem.Header>
      <StackPanel Orientation="Horizontal">
        <Ellipse Fill="Red" Width="20" Height="20" />
        <TextBlock Text="Third top-level item" />
        <Ellipse Fill="Red" Width="20" Height="20" />
      </StackPanel>
    </TreeViewItem.Header>
    <TreeViewItem Header="Child a" />
    <TreeViewItem Header="Child b" />
    <TreeViewItem Header="Child c" />
  </TreeViewItem>
</TreeView>
</Page>

Thứ Tư, 5 tháng 6, 2013

Code C#: Đưa hình ảnh vào thanh Trạng Thái (StatusBar)


<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="StatusBarSimple.Window1" Title ="StatusBar">
  <Window.Resources>
    <Style x:Key="StatusBarSeparatorStyle" TargetType="Separator">
      <Setter Property="Background" Value="LightBlue" />
      <Setter Property="Control.Width" Value="1"/>
      <Setter Property="Control.Height" Value="20"/>
    </Style>    
  </Window.Resources>
        <StatusBar Name="sbar" Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2" 
                   VerticalAlignment="Bottom" Background="Beige" > 
             <StatusBarItem>
                <Button Content="click" Click="MakeProgressBar"/>
             </StatusBarItem>
             <StatusBarItem>
               <Separator Style="{StaticResource StatusBarSeparatorStyle}"/>
             </StatusBarItem>
        </StatusBar>
</Window>
//File:Window.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace StatusBarSimple{
    public partial class Window1 : Window {
        private void MakeProgressBar(object sender, RoutedEventArgs e){
            sbar.Items.Clear();
            DockPanel dpanel = new DockPanel();
            TextBlock txtb = new TextBlock();
            txtb.Text = "Printing  ";
            dpanel.Children.Add(txtb);
            Image printImage = new Image();
            printImage.Width = 20;
            printImage.Height = 20;
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.UriSource = new Uri(@"pack://application:,,,/images/print.bmp");
            bi.EndInit();
            printImage.Source = bi;
            dpanel.Children.Add(printImage);
            TextBlock txtb2 = new TextBlock();
            txtb2.Text = "5pgs";
            dpanel.Children.Add(txtb2);
            StatusBarItem sbi = new StatusBarItem();
            sbi.Content = dpanel;
            sbi.HorizontalAlignment = HorizontalAlignment.Right;
            ToolTip ttp = new ToolTip();
            ttp.Content = "Sent to printer.";
            sbi.ToolTip = (ttp);
            sbar.Items.Add(sbi);
        }
    }
}

Chủ Nhật, 2 tháng 6, 2013

Code C#: Thêm các item (mục) vào Combo box


using System;
using System.Drawing;
using System.Windows.Forms;
public class Select : Form {
  private Button draw = new Button();
  private ComboBox color = new ComboBox();

  public Select( ) {
    draw.Text = "Draw";
    color.Text = "Choose a color";
    Size = new Size(400,240);

    int w = 20;
    draw.Location = new Point(20,30);
    color.Location = new Point(w += 10 + color.Width, 30);

    color.Items.Add("Black");
    color.Items.Add("Red");
    color.Items.Add("Blue");

    Controls.Add(draw);
    Controls.Add(color);

    draw.Click += new EventHandler(Draw_Click);
  } 

  protected void Draw_Click(Object sender, EventArgs e) {
    if (color.SelectedItem.ToString() == "Red" )
      Console.WriteLine("It is red.");
    else if (color.SelectedItem.ToString() == "Red")
      Console.WriteLine("It is Red.");
    else
      Console.WriteLine("It is blue.");
  }
  static void Main() {
    Application.Run(new Select());
  }
}

Thứ Bảy, 1 tháng 6, 2013

Code C#: Ràng buộc một TabControl đến nguồn dữ liệu


<Window x:Class="TabControlUsingItemTemplate.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:TabControlUsingItemTemplate"
    Title="TabControlUsingItemTemplate" Height="250" Width="250">
  <Window.Resources>
    <ObjectDataProvider x:Key="TabListResource" ObjectType="{x:Type src:TabList}" />
    <DataTemplate x:Key="HeaderTemplate">
      <TextBlock Text="{Binding Path=Header}" />
    </DataTemplate>
    <DataTemplate x:Key="ContentTemplate">
      <TextBlock Text="{Binding Path=Content}" />
    </DataTemplate>
  </Window.Resources>

  <DockPanel>
    <TabControl ItemsSource="{Binding Source={StaticResource TabListResource}}"
                  ItemTemplate="{StaticResource HeaderTemplate}"
                  ContentTemplate="{StaticResource ContentTemplate}"/>

  </DockPanel>

</Window>
//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace TabControlUsingItemTemplate
{
    public partial class Window1 : System.Windows.Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }
    public class TabItemData
    {
        private string _header;
        private string _content;

        public TabItemData(string header, string content)
        {
            _header = header;
            _content = content;
        }
        public string Header
        {
            get { return _header; }
        }
        public string Content
        {
            get { return _content; }
        }
    }
    public class TabList : ObservableCollection<TabItemData>
    {
        public TabList(): base()
        {

            Add(new TabItemData("Header 1", "Content 1"));
            Add(new TabItemData("Header 2", "Content 2"));
            Add(new TabItemData("Header 3", "Content 3"));

        }
    }
}

Thứ Sáu, 31 tháng 5, 2013

Code C#: Chuyển đổi văn bản sang hình học


<Window x:Class="GlyphExamples.GlyphClipping"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Glyph Clipping" Height="400" Width="360">
    <Grid HorizontalAlignment="Center" VerticalAlignment="Center" Width="80">
      <Grid.LayoutTransform>
        <ScaleTransform ScaleX="3" ScaleY="3" />
      </Grid.LayoutTransform>
      <Button x:Name="button1" Content="Click" />
    </Grid>
</Window>

//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;

namespace GlyphExamples
{
    public partial class GlyphClipping : System.Windows.Window
    {
        public GlyphClipping()
        {
            InitializeComponent();
            FormattedText text = new FormattedText("CLIP!",              Thread.CurrentThread.CurrentUICulture,  FlowDirection.LeftToRight, new Typeface("Gill Sans Ultra Bold"), 20, Brushes.Black);

            Geometry textGeometry = text.BuildGeometry(new Point(0, 0));
            button1.Clip = textGeometry;
        }
    }
}

Thứ Năm, 4 tháng 4, 2013

Code C#: MultiCast Delegate - Cơ chế ủy quyền (Delegate) đa phương thức trong C#



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyMulticastDelegate{
    public delegate void MulticastDelegate(int x, int y);

    public class Vidu2{
        public static void Cong(int x, int y) {
            Console.WriteLine("Ban dang goi phuong thuc Cong()");
            Console.WriteLine("{0} + {1} = {2}", x,y,x+y);
        }
        public static void Nhan(int x, int y) {
            Console.WriteLine("Ban dang goi phuong thuc Nhan()");
            Console.WriteLine("{0} x {1} = {2}", x, y, x * y);
        }
    }
    
    class Program{
        static void Main(string[] args){
            MulticastDelegate del = new MulticastDelegate(Vidu2.Cong);
            del += new MulticastDelegate(Vidu2.Nhan);
            Console.WriteLine("Goi dong thoi 2 phuong thuc Cong va Nhan\n\n");
            del(7, 6);

            del -= new MulticastDelegate(Vidu2.Cong);
            Console.WriteLine("\n\n****Da xoa phuong thuc Cong, chi goi phuong thuc Nhan****\n\n");
            del(4, 5);
            Console.ReadLine();
        }
    }
}


Code C#: Cơ chế ủy quyền (Delegate) trong C# (P.1)



Ví dụ 1: Khai báo cơ chế ủy quyền (delegate) trong C# gọi các phương thức thực thi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delegates{
    public delegate int MyDelegate(int x, int y);
    
    public class Vidu1{
        public static int Cong(int x, int y){
            return x + y;
        }
        public static int Nhan(int x, int y) {
            return x * y;
        }
    }
    
    class Program{
        static void Main(string[] args){
            MyDelegate del1 = new MyDelegate(Vidu1.Cong);
            int KetquaCong = del1(5, 5);
            Console.WriteLine("5 + 5 = {0}", KetquaCong);
            MyDelegate del2 = new MyDelegate(Vidu1.Nhan);
            int KetquaNhan = del2(5, 5);
            Console.WriteLine("5 x 5 = {0}", KetquaNhan);
            Console.ReadLine();
        }
    }
}


Thứ Ba, 26 tháng 3, 2013

Code C#: Xây dựng lớp trừu tượng và cách ghi đè phương thức trừu tượng ở lớp kế thừa


Xây dựng lớp trừu tượng Hình có thuộc tính PI, phương thức trừu tượng: TinhDienTich và TinhTheTich.
- Xây dựng lớp HinhTron kế thừa từ lớp Hinh, cài đặt phương thức ảo để tính diện tích, thể tích của hình tròn.
- Xây dựng lớp HinhLapPhuong kế thừa từ lớp Hinh, cài đặt phương thức ảo để tính diện tích, tính thể tích của hình lập phương.
namespaceLop_TruuTuong{
    abstract public class Hinh {
        protecteddouble PI = 3.14159;
        abstractpublic doubleTinhDienTich();
        abstractpublic doubleTinhTheTich();
    }
    public class HinhTron : Hinh {
        privatedouble bankinh;
        publicHinhTron(double r){
            this.bankinh = r;
        }
        public override doubleTinhDienTich(){
            returnPI * bankinh * bankinh;
        }
        public override doubleTinhTheTich() {
            return0;
        }
    }
    public class HinhLapPhuong : Hinh {
        privatedouble a, b, c;
        publicHinhLapPhuong(double a, double b, double c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }
        public override doubleTinhDienTich() {
            return2*(a*b + b*c + c*a);
        }
        public override doubleTinhTheTich() {
            returna * b * c;
        }
    }
    class Program
    {       
        public static void Main()
        {
            HinhTronht1 = new HinhTron(5);
            HinhLapPhuonghlp1 = new HinhLapPhuong(2, 3, 4);
            Console.WriteLine("Dien tich hinh tron: {0}. The tich hinh tron: {1}",ht1.TinhDienTich(),ht1.TinhTheTich());
            Console.WriteLine("Dien tich hinh lap phuong: {0}. The tich hinh lap phuong: {1}",hlp1.TinhDienTich(),hlp1.TinhTheTich());
            Console.ReadLine();           
        }
    }
}

Chủ Nhật, 24 tháng 3, 2013

Code C#: Bài tập cơ bản về LỚP (CLASS) - Thiết kế lớp SINH VIÊN


//Yêu cầu: Thiết kế lớp sinh viên bao gồm các thuộc tính:
- Họ tên, tuổi, điểm toán, điểm văn, điểm trung bình của 1 sinh viên. 
- Khai báo mảng sử dụng lớp sinh viên trên để nhập thông tin cho n sinh viên (n nhập từ bàn phím). 
- Tính điểm trung bình và in ra màn hình danh sách các sinh viên đó.
namespaceBaiThucHanhLop{      
        class Student{
            privatestring _hoTen;
            privateint _tuoi;
            privatedouble _diemToan;
            privatedouble _diemVan;
            privatedouble _dtb;
            //Hàm khởi tạo không có tham số
            publicStudent(){
                HoTen = "";
                DiemVan = 0;
                DiemToan = 0;
                Dtb = 0;
            }
            //Các phương thức Properties để get/set giá trị cho các thuộc tính
            publicstring HoTen{
                get{ return _hoTen; }
                set{ _hoTen = value; }
            }
            publicint Tuoi{
                get{ return _tuoi; }
                set{ _tuoi = value; }
            }
            publicdouble DiemToan{
                get{ return _diemToan; }
                set{ _diemToan = value; }
            }
            publicdouble DiemVan{
                get{ return _diemVan; }
                set{ _diemVan = value; }
            }
            publicdouble Dtb{
                get{ return Math.Round(((DiemToan + DiemVan) / 2), 2); }
                set{ _dtb = value; }
            }                    
            //Các phương thức nhập/xuất dữ liệu                    

            publicvoid nhap()
            {
                Console.Write(" \t -Nhap ho ten:");
                HoTen = Console.ReadLine();
                Console.Write(" \t -Nhap diem toan:");
                Doubletemp;
                temp = double.Parse(Console.ReadLine());
                if(temp > 10 || temp < 0)
                {
                    Console.WriteLine(" \t !!! Diem phai nam trong khoang 0 -> 10");
                    Console.Write(" \t -Nhap lai diem toan:");
                    temp = double.Parse(Console.ReadLine());
                }
                DiemToan = temp;

                Console.Write(" \t -Nhap diem van:");
                temp = double.Parse(Console.ReadLine());
                if(temp > 10 || temp < 0)
                {
                    Console.WriteLine(" \t -Diem phai nam trong khoang 0 -> 10");
                    Console.Write(" \t -Nhap lai diem Van:");
                    temp = double.Parse(Console.ReadLine());
                }
                DiemVan = temp;

            }
            publicvoid xuat(){
                Console.WriteLine("{0,-15}{1,-15}{2,-15}{3,-15}", HoTen, DiemToan, DiemVan, Dtb);
            }
        }

    class Program{       
        public static void Main(){
            intn;
            Console.Write(" Nhap so luong hoc sinh: ");
            n = int.Parse(Console.ReadLine());

            Student[] _arrStudent = new Student[n];
            for(int i = 0; i < n; i++){
                Console.WriteLine(" Nhap thong tin sinh vien thu: " + (i + 1).ToString());
                _arrStudent[i] = new Student();
                _arrStudent[i].nhap();
            }

            Console.WriteLine(" Danh sach hoc sinh: ");
            Console.WriteLine("{0,-15}{1,-15}{2,-15}{3,-15}", "Ho Ten", "Diem Toan", "Diem Van", "DTB");

            for(int i = 0; i < n; i++){
                _arrStudent[i].xuat();
            }
            Console.ReadLine();           
        }
    }
}

Thứ Năm, 21 tháng 3, 2013

Code C#: Tính tổng của n số (nhập từ bàn phím). Tìm giá trị lớn nhất, nhỏ nhất trong n số đó. Sử dụng MẢNG


//Yêu cầu: Viết chương trình Console Application. Tính tổng của n số nhập từ bàn phím. Tìm giá trị lớn nhất, giá trị nhỏ nhất trong n số đó. 
//Cách 1: Sử dụng mảng lưu trữ

class Program{
        static void Main(){
            intn,s=0;
            int[] a;
            Console.Write("Nhap so can tinh tong: ");
            n = int.Parse(Console.ReadLine());
            a = newint[n];
            for (inti = 0; i < n; i++){
                Console.Write("Nhap phan tu thu {0}: ",i+1);
                a[i] = int.Parse(Console.ReadLine());
            }
            for(int i = 0; i < n; i++){
                s += a[i];
            }
            for(int i = 0; i < n - 1; i++)
                for(int j = i; j < n;j++ )
                    if(a[i] <= a[j]) {
                        int tg = a[i];
                        a[i] = a[j];
                        a[j] = tg;
                    }
            Console.WriteLine("Tong cua {0} so nhap tu ban phim la: {1}", n, s);
            Console.WriteLine("Gia tri lon nhat: {0}",a[0]);
            Console.WriteLine("Gia tri nho nhat: {0}",a[n-1]);
            Console.ReadLine();
        }
}

Code C#: Nhập vào độ dài 3 đoạn. Kiểm tra 3 đoạn đó có tạo thành tam giác không? Và thuộc loại tam giác nào.


//Yêu cầu: Viết chương trình với loại ứng dụng Console Application, nhập vào 3 số. Kiểm tra xem đó có phải là 3 cạnh của một tam giác không. Nếu phải thì xem đó là loại tam giác gì.
class Program{
        static void Main(){
            floatx, y, z;
            Console.Write("Nhap chieu dai canh x: ");
            x = float.Parse(Console.ReadLine());
            Console.Write("Nhap chieu dai canh y: ");
            y = float.Parse(Console.ReadLine());
            Console.Write("Nhap chieu dai canh z: ");
            z = float.Parse(Console.ReadLine());
            if(x <= 0 || y <= 0 || z <= 0 || x + y <= z || y + z <= x || x + z <= y)
                Console.WriteLine("Ban nhap sai");
            else{
                if((x == y && x * x * 2 == z * z) || (x == z && x * x * 2 == y * y) || (y == z && y * y * 2 == x * x))
                    Console.WriteLine("Tam giac vuong can");
                else{
                    if(x == y && y == z && z == x)
                        Console.WriteLine("Tam giac deu");
                    else{
                        if (x == y || y == z || z == x)
                            Console.WriteLine("Tam giac can");
                        else
                            Console.WriteLine("Tam giac thuong");
                    }
                }
            }
            Console.ReadLine();
        }
}

Thứ Tư, 20 tháng 3, 2013

Code C#: Nhập vào số nguyên N có 4 chữ số. Tìm chữ số lớn thứ nhì trong 4 chữ số.


//Yêu cầu: Viết chương trình với loại ứng dụng Console Application, nhập vào số nguyên n có 4 chữ số. Hãy tìm chữ số lớn thứ nhì.
Ví dụ: n = 1895. n có 4 chữ số 1,8,9,5. Chữ số lớn thứ nhì: 8.
class Program{
        static void Main(){           
            intn;
            int[] a = new int[4];
            do{
                Console.Write("Nhập số n có 4 chữ số: ");
                n = int.Parse(Console.ReadLine());
            } while(n < 1000 || n > 9999);           
            for(int i = 0; i < 4; i++) {
                a[i] = n % 10;
                n = n / 10;
            }
            for(int i = 0; i < 3; i++)
                for(int j = i; j < 4;j++)
                    if(a[i] <= a[j]){
                        int tg = a[i];
                        a[i] = a[j];
                        a[j] = tg;
                    }            
            Console.WriteLine("So lon thu nhi trong 3 so la: {0}", a[1]);   
            Console.ReadLine();
        }
}

Thứ Hai, 18 tháng 3, 2013

Code C#: Nạp chồng toán tử (operator) trong C#


//Ví dụ minh họa nạp chồng toán tử (operator) ==, !=, + , - trong C# sử dụng implicit và explicit
using System;
public class Fraction{
publicFraction(int numerator, int denominator){
     Console.WriteLine("In Fraction Constructor(int, int)");
     this.numerator=numerator;
     this.denominator=denominator;
}
publicFraction(int wholeNumber){
     Console.WriteLine("In Fraction Constructor(int)");
     numerator = wholeNumber;
     denominator = 1;
}
public static implicit operator Fraction(inttheInt){
     System.Console.WriteLine("In implicit conversion to Fraction");
     return new Fraction(theInt);
}
public static explicit operator int(Fraction theFraction){
     System.Console.WriteLine("In explicit conversion to int");
     returntheFraction.numerator / theFraction.denominator;
}
public static bool operator==(Fraction lhs, Fraction rhs){
     Console.WriteLine("In operator ==");
     if(lhs.denominator == rhs.denominator &&
         lhs.numerator == rhs.numerator)
     {
        return true;
     }
     // code here to handle unlike fractions
     return false;
}
public static bool operator !=(Fraction lhs, Fraction rhs){
     Console.WriteLine("In operator !=");
     return!(lhs==rhs);
}
public override bool Equals(object o){
     Console.WriteLine("In method Equals");
     if (! (o is Fraction) ){
        return false;
     }
     return this == (Fraction) o;
}
public static Fraction operator+(Fraction lhs, Fraction rhs){
     Console.WriteLine("In operator+");
     if(lhs.denominator == rhs.denominator){
        return new Fraction(lhs.numerator+rhs.numerator,
         lhs.denominator);
     }
     // simplistic solution for unlike fractions
     // 1/2 + 3/4 == (1*4) + (3*2) / (2*4) == 10/8
     intfirstProduct = lhs.numerator * rhs.denominator;
     intsecondProduct = rhs.numerator * lhs.denominator;
     return new Fraction(
        firstProduct + secondProduct,
        lhs.denominator * rhs.denominator
        );
}
public override stringToString(){
     String s = numerator.ToString( ) + "/" +
        denominator.ToString( );
     return s;
}
private int numerator;
private int denominator;
}
public class Tester{
static void Main(){
     //implicit conversion to Fraction
     Fraction f1 = newFraction(3);
     Console.WriteLine("f1: {0}", f1.ToString( ));
     Fraction f2 = newFraction(2,4);
     Console.WriteLine("f2: {0}", f2.ToString( ));
     Fraction f3 = f1 + f2;
     Console.WriteLine("f1 + f2 = f3: {0}", f3.ToString());
     Fraction f4 = f3 + 5;
     Console.WriteLine("f3 + 5 = f4: {0}", f4.ToString());
     Fraction f5 = newFraction(2,4);
     if (f5 == f2){
        Console.WriteLine("F5: {0} == F2: {1}", f5.ToString(),
       f2.ToString());
     }
     int k = (int)f4; //explicit conversion to int
     Console.WriteLine("int: F5 = {0}", k.ToString());
}
}

Bài đăng phổ biến