레이블이 WPF인 게시물을 표시합니다. 모든 게시물 표시
레이블이 WPF인 게시물을 표시합니다. 모든 게시물 표시

2018/06/19

Extending the Shown Event in WPF


Using the Shown Event.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var eventExtend = this.EventExtend();
        eventExtend.AddShownEventHandler(this.MainWindow_Shown);
    }

    public void MainWindow_Shown(object sender, EventArgs e)
    {
            
    }
}

Fire the Shown Event using the LayoutUpdated Event.


public class FrameworkElementEventExtend
{
    public event EventHandler Shown;

    private bool initialized;
    private readonly FrameworkElement frameworkElement;

    public FrameworkElementEventExtend(FrameworkElement frameworkElement)
    {
        this.frameworkElement = frameworkElement;

        this.frameworkElement.LayoutUpdated += FrameworkElement_LayoutUpdated;
    }

    private void FrameworkElement_LayoutUpdated(object sender, EventArgs e)
    {
        if (!this.initialized && (this.frameworkElement.ActualHeight > 0 || this.frameworkElement.ActualWidth > 0))
        {
            this.Shown?.Invoke(this, EventArgs.Empty);

            this.initialized = true;

            this.frameworkElement.LayoutUpdated -= FrameworkElement_LayoutUpdated;
        }
    }
}

public static class FrameworkElementEventExtendHelper
{
    public static FrameworkElementEventExtend EventExtend(this FrameworkElement frameworkElement)
    {
        FrameworkElementEventExtend eventExtend = new FrameworkElementEventExtend(frameworkElement);
        return eventExtend;
    }

    public static void AddShownEventHandler(this FrameworkElementEventExtend eventExtend, EventHandler eventHandler)
    {
        eventExtend.Shown += eventHandler;
    }
}

2017/07/04

WPF 컬렉션 바인딩 과 그룹, 필터 및 정렬

WPF 컬렉션 바인딩 과 필터 및 정렬

모델

ComboBox에서 보기 좋은 출력을 위해 DisplayName 을 추가 한다.
public class ProductType
{
    public string ProductTypeId { get; set; }
    public string ProductTypeName { get; set; }
    public string GroupName { get; set; }
    public string DisplayName
    {
        get { return $"{this.GroupName}, {this.ProductTypeName}"; }
    }
}
 
public class Product
{
    public string ProductId { get; set; }
    public string ProductName { get; set; }
    public int Price { get; set; }
    public string ProductTypeId { get; set; }
}

컬렉션 객체


ObservableCollection<ProductType> productTypes = new ObservableCollection<ProductType>();
ObservableCollection<Product> products = new ObservableCollection<Product>();
 
productTypes.Add(new ProductType() { ProductTypeId = "1", ProductTypeName = "Server", GroupName = "Month" });
productTypes.Add(new ProductType() { ProductTypeId = "2", ProductTypeName = "Desktop", GroupName = "Month" });
productTypes.Add(new ProductType() { ProductTypeId = "3", ProductTypeName = "Server", GroupName = "Permanent" });
productTypes.Add(new ProductType() { ProductTypeId = "4", ProductTypeName = "Desktop", GroupName = "Permanent" });
 
products.Add(new Product() { ProductId = "1", ProductName = "Azure SQL", Price = 250, ProductTypeId = "1" });
products.Add(new Product() { ProductId = "2", ProductName = "Azure Web App", Price = 222, ProductTypeId = "1" });
products.Add(new Product() { ProductId = "3", ProductName = "Office 365", Price = 600, ProductTypeId = "2" });
products.Add(new Product() { ProductId = "4", ProductName = "OneDrive", Price = 100, ProductTypeId = "2" });

View - 정렬 및 그룹


var productTypeView = CollectionViewSource.GetDefaultView(productTypes);
productTypeView.SortDescriptions.Add(new System.ComponentModel.SortDescription(nameof(ProductType.ProductTypeName), System.ComponentModel.ListSortDirection.Ascending));
productTypeView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProductType.GroupName)));

View - 필터 및 정렬

Price 가 300 이하인 DataGrid 와 미만인 DataGrid 두개를 만들 것이다.
Price 업데이트 시 적용을 필터를 바로 적용하기 위하여 IsLiveFilteringRequested = true 를 사용하며 LiveFilteringProperties 에 Price 를 추가한다.
CollectionViewSource viewSource1 = new CollectionViewSource();
CollectionViewSource viewSource2 = new CollectionViewSource();
 
viewSource1.Source = this.products;
viewSource1.IsLiveFilteringRequested = true;
viewSource1.LiveFilteringProperties.Add(nameof(Product.Price));
viewSource1.View.Filter = (i) => (i as Product).Price <= 300;
 
viewSource2.Source = this.products;
viewSource2.IsLiveFilteringRequested = true;
viewSource2.LiveFilteringProperties.Add(nameof(Product.Price));
viewSource2.View.Filter = (i) => (i as Product).Price > 300;

소스 Binding


this.productTypeComboBox.ItemsSource = productTypeView;
this.gridProductTypeComboLowPrice.ItemsSource = productTypeView;
this.gridProductTypeComboHighPrice.ItemsSource = productTypeView;
 
this.dataGridLowPrice.ItemsSource = viewSource1.View;
this.dataGridHighPrice.ItemsSource = viewSource2.View;

Xaml

ComboBox는 그룹헤더로 구분 되여 출력을 한다.
<ComboBox Name="productTypeComboBox">
    <ComboBox.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
        </GroupStyle>
    </ComboBox.GroupStyle>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ProductTypeName}"></TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

DataGrid 에서 ProductType은 DisplayName을 출력 한다.
Price 300 이하은 DataGrid는 오름차순 정렬을 하고 초과하는 DataGrid는 내림차순 졍렬을 한다.
SelectedValueBinding, SelectedValuePath 두개의 속성으로 항목을 매핑을 하고 DisplayMemberPath로 표시 속성을 설정 한다.
<DataGrid Name="dataGridLowPrice" AutoGenerateColumns="False" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="ProductName" Binding="{Binding ProductName}" />
        <DataGridTextColumn Header="Price" Binding="{Binding Price}" SortDirection="Ascending" />
        <DataGridComboBoxColumn x:Name="gridProductTypeComboLowPrice" Header="ProductType" SelectedValueBinding="{Binding ProductTypeId}" SelectedValuePath="ProductTypeId" DisplayMemberPath="DisplayName" />
    </DataGrid.Columns>
</DataGrid>                    
<DataGrid Name="dataGridHighPrice" AutoGenerateColumns="False" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="ProductName" Binding="{Binding ProductName}" />
        <DataGridTextColumn Header="Price" Binding="{Binding Price}" SortDirection="Descending" />
        <DataGridComboBoxColumn x:Name="gridProductTypeComboHighPrice" Header="ProductType" SelectedValueBinding="{Binding ProductTypeId}" SelectedValuePath="ProductTypeId" DisplayMemberPath="DisplayName" />
    </DataGrid.Columns>
</DataGrid> 

결과 화면

ComboBox Group 적용
ComboBox Group 적용

DataGrid ComboBox DisplayName적용
DataGrid ComboBox DisplayName적용

2017/06/27

WPF 에서 WebApi 인증

WPF 에서 WebApi 인증

RoleProvider 생성


public class TestRoleProvider : RoleProvider
{
    //생략...
 
    public override string[] GetRolesForUser(string username)
    {
        string[] roles = { "Member" };//get roles by username
 
        return roles;
    }
}

RoleProvider 및 인증 설정


<system.web>
  <authentication mode="Forms">
    <forms loginUrl="~/member/login" timeout="20" slidingExpiration="true" />
  </authentication>
  <roleManager enabled="true" defaultProvider="TestRoleProvider">
    <providers>
      <clear />
      <add name="TestRoleProvider" type="WebApiTest.TestRoleProvider" />
    </providers>
  </roleManager>
</system.web>

권한 필터 설정


public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new AuthorizeAttribute());
    }
}

Action에 권한 설정


public class ItemController : ApiController
{
    Item[] items = new Item[]
    {
    new Item { Id = "google", Name = "Google" },
    new Item { Id = "naver", Name = "Naver" },
    new Item { Id = "daum", Name = "Daum" }
    };
 
    [System.Web.Http.Authorize(Roles = "Member")]
    public IEnumerable<Item> GetAllItems()
    {
        return items;
    }
}

public class MemberController : Controller
{
    [HttpPost]
    [System.Web.Mvc.AllowAnonymous]
    public ActionResult Login(string userId, string password)
    {
        //사용자 유효성 검사
        if (userId == "test" && password == "1234")
        {
            //인증쿠키 설정
            System.Web.Security.FormsAuthentication.SetAuthCookie(userId, false);
            return new HttpStatusCodeResult(System.Net.HttpStatusCode.OK);
        }
 
        return new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized);
    }
}

HttpClient 로그인


private Uri uri = new Uri("http://localhost:59791");
private CookieContainer cookies = new CookieContainer();
private HttpClientHandler handler = new HttpClientHandler();
private HttpClient client;
 
private ItemCollection items = new ItemCollection();
 
public MainWindow()
{
    InitializeComponent();
 
    this.handler.CookieContainer = this.cookies;
    this.client = new HttpClient(this.handler);
 
    this.client.BaseAddress = uri;
 
    this.Login();
 
    this.client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
 
 
    this.ItemsList.ItemsSource = this.items;
}
 
public HttpStatusCode Login()
{
    var result = this.client.PostAsync("member/login",
        new FormUrlEncodedContent(
        new Dictionary<string, string>
        {
            {"userId", "test"},
            {"password", "1234"}
        }
        )
    ).Result;
 
    return result.StatusCode;
}

WebApi 사용


private async void GetItems(object sender, RoutedEventArgs e)
{
    var response = await client.GetAsync("api/item/getallitems");
    response.EnsureSuccessStatusCode();
 
    var items = await response.Content.ReadAsAsync<IEnumerable<Item>>();
    this.items.CopyFrom(items);
}

WPF 에서 WebApi 사용하기

WPF 에서 WebApi 사용하기

Model

public class Item
{
    public string Id { get; set; }
    public string Name { get; set; }
}

WebAPI

public class ItemController : ApiController
{
    Item[] items = new Item[]
    {
        new Item { Id = "google", Name = "Google" },
        new Item { Id = "naver", Name = "Naver" },
        new Item { Id = "daum", Name = "Daum" }
    };
 
    public IEnumerable<Item> GetAllItems()
    {
        return items;
    }
}

WPF ObservableCollection

public class ItemCollection : ObservableCollection<Item>
{
    public void CopyFrom(IEnumerable<Item> items)
    {
        this.Items.Clear();
        foreach (var p in items)
        {
            this.Items.Add(p);
        }
 
        this.OnCollectionChanged(
            new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

WPF View

<StackPanel Width="250" >
    <Button Name="getAllItemsButton" Click="GetItems">Get Items</Button>
    <ListBox Name="ItemsList">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="2">
                    <TextBlock >Id: <Run Text="{Binding Path=Id}" /></TextBlock>
                    <TextBlock >Name: <Run Text="{Binding Path=Name}" /></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

WPF Code

비동기 호출을 사용하여 사용자 응답성을 향상 시킨다.

public partial class MainWindow : Window
{
    HttpClient client = new HttpClient();
    ItemCollection items = new ItemCollection();
 
    public MainWindow()
    {
        InitializeComponent();
 
        client.BaseAddress = new Uri("http://localhost:59791");
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
 
        this.ItemsList.ItemsSource = this.items;
    }
 
    private async void GetItems(object sender, RoutedEventArgs e)
    {
        try
        {
            this.getAllItemsButton.IsEnabled = false;
 
            var response = await client.GetAsync("api/item/getallitems");
            response.EnsureSuccessStatusCode(); 
 
            var items = await response.Content.ReadAsAsync<IEnumerable<Item>>();
            this.items.CopyFrom(items);
        }
        catch (Newtonsoft.Json.JsonException jEx)
        {
            MessageBox.Show(jEx.Message);
        }
        catch (HttpRequestException ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            this.getAllItemsButton.IsEnabled = true;
        }
    }
}

C# 문자열 포함 여부 확인하기.

ToUpper() 를 사용하면 불필요한 문자열을 생성하므로 좋은 방법은 아니다. string text = "This is an apple." ; string apple = "Apple." ; bool ...